Creating Your Own Exception Subclasses

You can create your own exception class by defining a subclass of Exception.

The Exception class does not define any methods of its own. It inherits methods provided by Throwable.

All exceptions have the methods defined by Throwable available to them. They are shown in the following list.

Throwable fillInStackTrace( )
Returns a Throwable object that contains a completed stack trace.
Throwable getCause( )
Returns the exception that underlies the current exception.
String getLocalizedMessage( )
Returns a localized description.
String getMessage( )
Returns a description of the exception.
StackTraceElement[ ] getStackTrace( )
Returns an array that contains the stack trace.
Throwable initCause(Throwable causeExc)
Associates causeExc with the invoking exception as a cause of the invoking exception.
void printStackTrace( )
Displays the stack trace.
void printStackTrace(PrintStream stream)
Sends the stack trace to the stream.
void printStackTrace(PrintWriter stream)
Sends the stack trace to the stream.
void setStackTrace(StackTraceElement elements[ ])
Sets the stack trace to the elements passed in elements.
String toString( )
Returns a String object containing a description of the exception.

The following program creates a custom exception type.


class MyException extends Exception {
  private int detail;

  MyException(int a) {
    detail = a;
  }

  public String toString() {
    return "MyException[" + detail + "]";
  }
}

public class Main {
  static void compute(int a) throws MyException {
    System.out.println("Called compute(" + a + ")");
    if (a > 10)
      throw new MyException(a);
    System.out.println("Normal exit");
  }

  public static void main(String args[]) {
    try {
      compute(1);
      compute(20);
    } catch (MyException e) {
      System.out.println("Caught " + e);
    }
  }
}
Home 
  Java Book 
    Language Basics  

Exception Handler:
  1. Exception Handling
  2. Exception Types
  3. try and catch
  4. Displaying a Description of an Exception
  5. Multiple catch Clauses
  6. Nested try Statements
  7. Creates and throws an exception
  8. Methods with throws clause
  9. finally
  10. Java's Built-in Exceptions
  11. Creating Your Own Exception Subclasses
  12. Chained Exceptions