Throwable class is the superclass of all exception classes in Java.
All of the methods shown in this table are available in all exception classes.
A Partial List of Methods of the Throwable Class
Method | Description |
---|---|
Throwable getCause() | It returns the cause of the exception. If the cause of the exception is not set, it returns null. |
String getMessage() | It returns the detailed message of the exception. |
StackTraceElement[] getStackTrace() | It returns an array of stack trace elements. |
Throwable initCause(Throwable cause) | There are two ways to set an exception as the cause of an exception. One way is to use the constructor, which accepts the cause as a parameter. Another way is to use this method. |
void printStackTrace() | It prints the stack trace on the standard error stream. |
void printStackTrace(PrintStream s) | It prints the stack trace to the specified PrintStream object. |
void printStackTrace(PrintWriter s) | It prints the stack trace to the specified PrintWriter object. |
String toString() | It returns a short description of the exception object. The description of an exception object contains the name of the exception class and the detail message. |
Printing the Stack Trace of an Exception
public class Main { public static void main(String[] args) { try {/* w w w . j ava 2 s . co m*/ m1(); } catch (MyException e) { e.printStackTrace(); // Print the stack trace } } public static void m1() throws MyException { m2(); } public static void m2() throws MyException { throw new MyException("Some error has occurred."); } } class MyException extends Exception { public MyException() { super(); } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } }