In Java, the Throwable class is at the top of the exception hierarchy. Both the Error and Exception classes extend Throwable. The Throwable class itself provides several methods that are commonly used when dealing with exceptions.
What are the Built-In Exception Methods?
The Throwable class offers a set of methods to help users work with exceptions. Since all exceptions are subclasses of Throwable, all exceptions inherit the methods provided by Throwable.
Subclasses also have the option to override the set of methods to perform a more tailored task. A list of a few commonly used methods and their uses are provided below.
| Method | Description |
|---|---|
| Throwable fillInStackTrace() | Returns a Throwable object that contains a completed stack trace |
| String getLocalizedMessage() | Returns a localized description of the exception |
| String getMessage() | Returns a description of the exception |
| String getCause() | Returns the cause of the exception |
| void printStackTrace() | Displays the stack trace |
| String toString() | Returns a String object containing a description of the exception |
Throwable Methods Examples
Here are a few examples to demonstrate.
Example of printStackTrace()
Prints the stack trace of the exception to the standard error stream. This includes the sequence of method calls that led to the exception.
public static void main(String[] args){
try {
// some code that may throw an exception
} catch (ArrayIndexOutOfBoundsException exc){
exc.printStackTrace();
}
}
Example of getMessage()
Returns a detailed message string about the exception. If no message is set, it returns null.
try {
// some code that may throw an exception
} catch (Exception e) {
System.out.println(e.getMessage());
}
Example of toString()
Returns a string representation of the exception, including the class name and the detailed message.
try {
// some code that may throw an exception
} catch (Exception e) {
System.out.println(e.toString());
}
Example of getCause()
Returns the cause of the exception, or null if the cause is unknown or nonexistent.
try {
// some code that may throw an exception
} catch (Exception e) {
Throwable cause = e.getCause();
// handle the cause
}
Example of printStackTrace()
Prints the stack trace of the exception to the standard error stream. This includes the sequence of method calls that led to the exception.
try {
// some code that may throw an exception
} catch (Exception e) {
e.printStackTrace();
}
Summary: Java Exception's Methods
- All exceptions in Java come with pre-built methods
printStackTrace()is an example of one of the methods- When dealing with a new class (or Exception) it is always a good idea to quickly look at the various methods that class (or Exception) provides