Class Throwable
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause. For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.
Instances of two subclasses, Error and Exception , are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).
A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Over time, a throwable can suppress other throwables from being propagated. Finally, the throwable can also contain a cause: another throwable that caused this throwable to be constructed. The recording of this causal information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a «chain» of exceptions, each caused by another.
One reason that a throwable may have a cause is that the class that throws it is built atop a lower layered abstraction, and an operation on the upper layer fails due to a failure in the lower layer. It would be bad design to let the throwable thrown by the lower layer propagate outward, as it is generally unrelated to the abstraction provided by the upper layer. Further, doing so would tie the API of the upper layer to the details of its implementation, assuming the lower layer’s exception was a checked exception. Throwing a «wrapped exception» (i.e., an exception containing a cause) allows the upper layer to communicate the details of the failure to its caller without incurring either of these shortcomings. It preserves the flexibility to change the implementation of the upper layer without changing its API (in particular, the set of exceptions thrown by its methods).
A second reason that a throwable may have a cause is that the method that throws it must conform to a general-purpose interface that does not permit the method to throw the cause directly. For example, suppose a persistent collection conforms to the Collection interface, and that its persistence is implemented atop java.io . Suppose the internals of the add method can throw an IOException . The implementation can communicate the details of the IOException to its caller while conforming to the Collection interface by wrapping the IOException in an appropriate unchecked exception. (The specification for the persistent collection should indicate that it is capable of throwing such exceptions.)
A cause can be associated with a throwable in two ways: via a constructor that takes the cause as an argument, or via the initCause(Throwable) method. New throwable classes that wish to allow causes to be associated with them should provide constructors that take a cause and delegate (perhaps indirectly) to one of the Throwable constructors that takes a cause. Because the initCause method is public, it allows a cause to be associated with any throwable, even a «legacy throwable» whose implementation predates the addition of the exception chaining mechanism to Throwable .
By convention, class Throwable and its subclasses have two constructors, one that takes no arguments and one that takes a String argument that can be used to produce a detail message. Further, those subclasses that might likely have a cause associated with them should have two more constructors, one that takes a Throwable (the cause), and one that takes a String (the detail message) and a Throwable (the cause).
Understanding Exception Stack Trace in Java with Code Examples
This Java exception tutorial helps you understand the concept of exception stack trace in Java and how to analyze an exception stack trace to detect bugs.
In this tutorial, we use the example in the article Understanding Java Exception Chaining with Code Examples. So kindly refer to that article while reading this one.
1. Analyzing an Exception Stack Trace
StudentException: Error finding students at StudentManager.findStudents(StudentManager.java:13) at StudentProgram.main(StudentProgram.java:9) Caused by: DAOException: Error querying students from database at StudentDAO.list(StudentDAO.java:11) at StudentManager.findStudents(StudentManager.java:11) . 1 more Caused by: java.sql.SQLException: Syntax Error at DatabaseUtils.executeQuery(DatabaseUtils.java:5) at StudentDAO.list(StudentDAO.java:8) . 2 more
By examining this information we can find the root cause of the problem in order to fix bugs. In this exception stack trace, you see a list of chained exceptions which is sorted by the exception at the highest level to the one at the lowest level. This forms a stack like a stack of cards.
In each trace, we see the exception type (exception class name) along with the message:
StudentException: Error finding students
at StudentManager.findStudents(StudentManager.java:13)
This line tells us that the StudentException was thrown at line 13 in the method findStudents() of the class StudentManager.
And what causes the StudentException ? Look at the next trace, we see:
Caused by: DAOException: Error querying students from database
That means the StudentException is caused by the DAOException which is thrown at line 11 in the method list() of the StudentDAO class.
Continue investigating further until the last exception in the trace, we see that the SQLException is actually the root cause and the actual place that sparks the exception is at line 5 in the method executeQuery() of the DatabaseUtils class:
Caused by: java.sql.SQLException: Syntax Error at DatabaseUtils.executeQuery(DatabaseUtils.java:5)
import java.sql.*; public class DatabaseUtils < public static void executeQuery(String sql) throws SQLException < throw new SQLException("Syntax Error"); >>
So basically that’s how we analyze the exception stack trace to find the root cause of the bug. The root cause is always at the bottom of the stack.
2. Preventing Exceptions Lost
Chaining exceptions together is a good practice, as it prevents exceptions from losing in the stack trace. Let’s modify the StudentDAO class like this:
import java.sql.*; public class StudentDAO < public void list() throws DAOException < try < DatabaseUtils.executeQuery("SELECT"); >catch (SQLException ex) < throw new DAOException("Error querying students from database"); >> >
Here we remove the SQLException instance ( ex ) from the DAOException ’s constructor. Let’s compile and run the StudentProgram again, we would get the following output:
StudentException: Error finding students at StudentManager.findStudents(StudentManager.java:13) at StudentProgram.main(StudentProgram.java:11) Caused by: DAOException: Error querying students from database at StudentDAO.list(StudentDAO.java:11) at StudentManager.findStudents(StudentManager.java:11) . 1 more
By comparing this exception stack trace with the previous one, we see that the SQLException disappears, right? That means the SQLException is lost in the stack trace though it is actually the root cause. When this happens, it’s hard to detect bugs exactly as the truth is hidden.
So you understand the importance of chaining exceptions together, don’t you?
3. Working with Exception Stack Trace
Besides the printStackTrace() method which prints out the detail exception stack trace, the Throwable class also provides several methods for working with the stack trace. Here I name a few.
- The printStackTrace(PrintStream) method writes the stack trace to a file stream. For example:
> catch (StudentException ex) < try < PrintStream stream = new PrintStream(new File("exceptions1.txt")); ex.printStackTrace(stream); stream.close(); >catch (FileNotFoundException fne) < fne.printStackTrace(); >>
> catch (StudentException ex) < // print stack trace to a PrintWriter try < PrintWriter writer = new PrintWriter(new File("exceptions2.txt")); ex.printStackTrace(writer); writer.close(); >catch (FileNotFoundException fne) < fne.printStackTrace(); >>
> catch (StudentException ex) < StackTraceElement[] stackTrace = ex.getStackTrace(); for (StackTraceElement trace : stackTrace) < String traceInfo = trace.getClassName() + "." + trace.getMethodName() + ":" + trace.getLineNumber() + "(" + trace.getFileName() + ")"; System.out.println(traceInfo); >>
Consult the Javadoc of the Throwable class to see more methods like fillInStackTrace() , setStackTrace() , etc.
4. A good practice about exception handling
Don’t handle exceptions in the intermediate layers, because code in the middle layers is often used by code in the higher layers. It’s responsibility of the code in the top-most layer to handle the exceptions. The top-most layer is typically the user interface such as command-line console, window or webpage. And typically we handle exceptions by showing a warning/error message to the user.
This good practice is illustrated by the following picture:
So remember this rule when designing and coding your program.
References:
Other Java Exception Handling Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.