Throwable Methods: getMessage, printStackTrace, and getCause
You'll learn how to extract diagnostic information from any exception or error using three essential methods inherited from Throwable.
Understanding Throwable's Diagnostic Tools
Every exception and error in Java inherits from Throwable, which provides several methods to help you understand what went wrong. The three most important methods are getMessage(), printStackTrace(), and getCause().
getMessage(): The Human-Readable Summary
getMessage() returns a String describing what happened. This is the message you provide when creating an exception:
try {
throw new RuntimeException("File not found: data.txt");
} catch (RuntimeException e) {
String message = e.getMessage();
System.out.println(message); // Prints: File not found: data.txt
}
printStackTrace(): The Full Diagnostic Report
printStackTrace() prints the exception's class name, message, and the complete call stack showing where the exception occurred and how execution got there. Think of it as a roadmap showing the journey through your code that led to the problem:
try {
throw new RuntimeException("Something broke");
} catch (RuntimeException e) {
e.printStackTrace(); // Prints detailed stack trace to console
}
getCause(): Finding the Root Problem
getCause() returns the underlying exception that caused this one, or null if there isn't one. This is useful when exceptions are wrapped:
try {
// Some code that throws an exception
} catch (Exception e) {
Throwable cause = e.getCause();
if (cause != null) {
System.out.println("Root cause: " + cause.getMessage());
}
}
Key Takeaway: Use getMessage() for a brief description, printStackTrace() for detailed debugging information, and getCause() to unwrap exception chains and find the original problem.