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);
}
}
}