Published: July 15, 2002
By Richard G. Baldwin
Java Programming Notes # 57
Here is how Sun describes the cause facility:
"A throwable ... can contain a cause: another throwable that caused this throwable to get thrown. The cause facility is new in release 1.4. It is also known 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..."Sun goes on to say:
"This new facility provides a common API to record the fact that one exception caused another, to access causative exceptions, and to access the entire "causal chain" as part of the standard stack backtrace, ensuring that preexisting programs will provide this information with no additional effort on the part of their authors."In this lesson, I well teach you how to use the chained exception facility that is now available.
Viewing tip
You may find it useful to open another copy of this lesson in a separate browser window. That will make it easier for you to scroll back and forth among the different listings and figures while you are reading about them.
Supplementary material
I recommend that you also study the other lessons in my extensive collection of online Java tutorials. You will find those lessons published at Gamelan.com. However, as of the date of this writing, Gamelan doesn't maintain a consolidated index of my Java tutorial lessons, and sometimes they are difficult to locate there. You will find a consolidated index at Baldwin's Java Programming Tutorials.
The exception-handling capability of Java makes it possible for you to:
This is accomplished using the keywords: try, catch, throw, throws, and finally. The basic concept is as follows:
There are also situations where you don't write the code to throw the exception object. Rather, the code in a method that you call throws an exception, or you attempt to execute some code that causes the runtime system to throw an exception (such as integer divide by zero).
When an exceptional condition causes an exception to be thrown, that exception is represented by an object instantiated from the class named Throwable or one of its subclasses.
Throwable constructors and methods
All errors and exceptions are subclasses of the
Throwable class.
As of JDK 1.4.0, the Throwable class provides four constructors
and about a dozen methods. The four constructors are shown in Figure
1.
Throwable() Throwable(String message) Throwable(String message, Throwable cause) Throwable(Throwable cause) Figure 1 |
The first two constructors have been in Java for a very long time. Basically, these two constructors allow you to construct an exception object with or without a String message encapsulated in the object.
New to JDK 1.4
The last two constructors (highlighted in boldface) are new to JDK 1.4. These two constructors are provided to support the cause facility, otherwise known as chained exceptions.
Catch blocks can throw exceptions
According to Sun, "It is common for Java code to catch one exception
and throw another." Typically, this involves the use of code
such as that shown in Figure 2.
try{
//... }//end try block catch(OneExceptionType e){ throw new AnotherExceptionType(); }//end catch block Figure 2 |
A problem with this has always been that information about the first exception has generally been lost when the second exception was thrown. This did not work well insofar as debugging is concerned.
Homebrew and non-standard schemes have been in use
As a result, many developers have developed homebrew schemes for implementing chained exceptions, wherein they wrapped information about the first exception inside the information encapsulated in the object thrown inside the catch block a higher level. This has led to non-standard approaches, some of which worked better than others.
Also, while referring to the standard class libraries, Sun has this to say:
"Prior to release 1.4, there were many throwables that had their own non-standard exception chaining mechanisms ... As of release 1.4, all of these throwables have been retrofitted to use the standard exception chaining mechanism, while continuing to implement their "legacy" chaining mechanisms for compatibility."Advantages of a unified system for exception chaining
Apparently, Sun decided to unify these facilities, and they list the following advantages of doing so:
Sun goes on to point out that with respect to the third advantage, the printStackTrace method has been upgraded such that it prints the entire causal chain as part of the standard stack backtrace. This ensures that preexisting programs will provide this information with no additional effort on the part of their authors. You will see an example of this in the sample program later in this lesson.
Two new methods support cause facility
In addition to the two new constructors mentioned earlier, Sun added two new methods to the Throwable class to support the new cause facility:
General-purpose exception classes upgraded
In addition to the Throwable class, other general-purpose exception classes, such as Exception, RunTimeException, and Error, were upgraded to support the two new overloaded constructors. As you will see in the sample program later, even exceptions without such upgraded constructors (such as DOMException, for example) will be usable as wrapped exceptions via the initCause method.
Programmatic access to the stack trace for
In addition to upgrading the printStackTrace method as described above, a new getStackTrace method was added, which provides programmatic access to the same stack trace information that is displayed by the printStackTrace method. This makes it possible for you to write code that can make decisions on the basis of information contained in the stack trace.
Now back to the Throwable class
Whenever an error or an exception occurs, an object is thrown. That object must be instantiated from the class Throwable, or a subclass of Throwable. A Throwable object contains a snapshot of the execution stack of its thread at the time it was created. As mentioned above, there are a couple of methods that provide access to that snapshot:
The Throwable object can also contain a message string that provides information about the error or the exception. With the advent of version 1.4, the Throwable object can also contain a cause.
What is a cause?
A cause is a reference to another Throwable object. The intent is that this object will be interpreted as the thing that caused this throwable to get thrown in the first place.
(However, you could encapsulate any Throwable object in a new Throwable object, whether or not it had anything to do with the true cause. All that you are required to do is pass a Throwable object's reference to the constructor for a new Throwable object, or invoke the initCause method on an existing Throwable object, passing a reference to another Throwable object as a parameter. It then becomes a cause.)Two ways to encapsulate a cause
As suggested above, you can associate a cause with a Throwable in two different ways. One way is to invoke one of the constructors that accepts a Throwable as a parameter. This assumes, of course, that the class from which you are instantiating the new object has such a constructor. You will see an example of this in the sample program later in this lesson.
The other way to associate a cause with a Throwable is to invoke the initCause method on an existing Throwable object's reference, passing a reference to another Throwable object as a parameter. This works even when you are instantiating a new object from a class that doesn't have a constructor that accepts a parameter of type Throwable.
Support for legacy exception classes
According to Sun:
"... the initCause method ... 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."I will apply the initCause method to an IndexOutOfBoundsException object in the sample program later in this lesson. According to the first edition of Java in a Nutshell, by David Flanagan, this exception type has been part of Java for at least as far back as release 1.1.
Define four constructors in new exception classes
If you define a new Throwable class and wish for an object of that class to have a cause associated with it, you should define constructors that take a Throwable as a parameter and pass that Throwable up the inheritance hierarchy to one of the Throwable constructors that takes a Throwable as a parameter. (Your new class should have one constructor that matches the formal argument list of each of the four constructors in the Throwable class). You will see an example of this in the sample program.
Sample program named Excep20
Now it's time to take a look at some code. A complete listing of the program named Excep20 is shown in Listing 7 near the end of the lesson. I will discuss this program in fragments.
Two new exception classes
This program defines two new classes, named NewEx01 and NewEx02,
which are used to instantiate and throw exception objects. The code
in each of these classes is essentially the same, so I will show and discuss
only one of them. The class named NewEx01 is shown in Listing
1.
class NewEx01 extends Exception{ public NewEx01() { }//end constructor public NewEx01(String message){ super(message); }//end constructor public NewEx01(Throwable throwable){ super(throwable); }//end constructor public NewEx01(String message, Throwable throwable){ super(message, throwable); }//end constructor }//end NewEx01 Listing 1 |
A checked exception class
As you can see from Listing 1, the class extends Exception. As a result, it is a checked exception class. (Of course, it is also a Throwable class, because Exception extends Throwable.).
Four overloaded constructors
As suggested in an earlier paragraph, the code in the class definition consists of four overloaded constructors, each corresponding to one of the four overloaded constructors in the Throwable class.
Each constructor (other than the one that takes no arguments) uses the super keyword to pass the incoming parameters up to the constructor for the superclass. This makes it possible to invoke the methods of the Throwable class on an object instantiated from this class, and have those methods behave correctly.
Summary of the program's behavior
Basically, this program consists of the controlling named Excep20, two exception classes named NewEx01 and NewEx02, and another class named Class01.
The class named Class01 defines three methods named meth01, meth02, and meth03. The main method of the controlling class instantiates a new object of the class Class01, and invokes the method named meth01 on that object's reference.
The method named meth01 invokes the method named meth02, and the method named meth02 invokes the method named meth03.
Oops! meth03 throws an exception
The code in meth03 attempts to perform an integer divide by zero, causing an ArithmeticException to be thrown by the runtime system. This code is executed inside a try block. A catch block that follows the try block catches the ArithmeticException.
Instantiate and throw a different exception with a cause
Code in the catch block instantiates a new object of type IndexOutOfBoundsException and invokes the initCause method on that object, causing it to encapsulate a reference to the ArithmeticException that was caught by the catch block. Then it throws the IndexOutOfBoundsException object, which is caught by the method named meth02 (the next method up the call stack).
Instantiate and throw a different exception with a cause - again
The method named meth02 catches that object and encapsulates it in an object of type NewEx02, which it throws.
This exception is caught by meth01, which performs a similar action, and throws an object of type NewEx01, which is caught by the main method.
Print information at each stop along the way
At each stop along the way, the method catching the exception object displays certain information about the object that it caught, including the message and the cause encapsulated in that object.
Print the stack trace
Finally, the main method prints a stack trace showing the complete history of the call stack since the ArithmeticException was thrown way down in the method named meth03.
Code from the inside out
I am going to discuss the code from the inside out. Listing 3
shows the method named meth03, where the ArithmeticException
gets thrown as a result of an attempt to perform an integer divide by zero.
void meth03(){ try{ int x = 3/0; }//end try block catch(ArithmeticException e){ IndexOutOfBoundsException ex = new IndexOutOfBoundsException( "Msg from metho03"); ex.initCause(e); throw ex; }//end catch block }//end meth03 Listing 2 |
Why throw an IndexOutOfBoundsException object?
You may be wondering why I chose to have this method throw an IndexOutOfBoundsException object, since this program has absolutely nothing to do with an index.
I wanted to demonstrate the use of the initCause method to encapsulate the reference to the ArithmeticException object (as the cause) in an object instantiated from a class that predates release 1.4. As near as I can tell, the IndexOutOfBoundsException class has been part of Java for as least as far back as release 1.1.
The meth03 method implements try/catch exception handling
As you can see in Listing 2, the code in meth03 consists of a try block followed by a catch block. The code in the try block attempts to perform an integer divide by zero, causing an ArithmeticException to be thrown.
This exception is caught in the catch block, where the incoming reference to the ArithmeticException object is known locally by the name e
Instantiate a new IndexOutOfBoundsException object
The code in the catch block instantiates a new object of the class IndexOutOfBoundsException, saving the object's reference in the reference variable named ex.
Encapsulate the cause
Then the code in the catch block invokes the initCause method on that reference variable, passing the ArithmeticException object's reference as a parameter. The initCause method is new to JDK 1.4. In this case, it causes the ArithmeticException object's reference to be encapsulated in the IndexOutOfBoundsException object as a cause.
As we will see shortly, the getCause method can later be invoked on the reference to that object to get access to the original ArithmeticException object.
Throw the exception
The code in meth03 then throws the IndexOutOfBoundsException object, and that terminates the catch block.
Find an appropriate handler
At this point, the runtime system starts searching for a catch block capable of accepting an incoming object reference of type IndexOutOfBoundsException. This could be a catch block designed to accept a parameter of type IndexOutOfBoundsException, or any superclass of IndexOutOfBoundsException.
Such a catch block is found in the method named meth02, which is the method that originally called meth03. In other words, the method named meth02 is the next method encountered when moving up through the call stack.
The code for the method named meth02 is shown in Listing 3.
void meth02() throws NewEx02{ try{ meth03(); }//end try catch(RuntimeException e){ System.out.println( "In meth02 catch block"); System.out.println( "Msg is:\n" + e.getMessage()); System.out.println( "Cause is:\n" + e.getCause()); System.out.println(); throw new NewEx02( "Msg from meth02",e); }//end catch }//end meth02 Listing 3 |
This method also has a try block followed by a catch block. The try block contains a single statement, which is a call to the method named meth03. (This is how control reached meth03 in the first place.) As we saw in Listing 2, meth03 throws an IndexOutOfBoundsException, which is a subclass of RuntimeException.
Not a checked exception
Because it is a subclass of RuntimeException, it is not a checked exception. Therefore, it is not necessary for meth03 to declare that it throws the exception.
However, even though the exception is not declared in the signature for meth03, the author of meth02 can still elect to monitor for and catch the exception if it gets thrown. (The purposeful handling of unchecked exceptions is optional.)
As the author of meth02, I did elect to monitor for and handle all exceptions of type RuntimeException. Hence, the parameter type specified in the catch block in meth02 is RuntimeException. The reference to any RuntimeException that may be caught is known locally by the name e within the catch block.
Behavior of the catch block in meth02
The code in the catch block in Listing 3 begins by getting and
displaying the message and the cause encapsulated in the incoming
object of type RuntimeException. The output is similar to
that shown in Figure 3. (I manually inserted some newline
characters to force the material to fit in this narrow format.)
In meth02 catch block Msg is: Msg from metho03 Cause is: java.lang.ArithmeticException: / by zero Figure 3 |
The output
The ability to get and display the message encapsulated in an incoming exception object has been a part of Java for a very long time. However, the ability to get and display the cause, by invoking the getCause method on the exception object, (which is highlighted in boldface in Listing 3), is new to JDK 1.4. (The result of invoking the getCause method in Listing 3 is highlighted in boldface in the output shown in Figure 3.)
Format of cause information
Note that in this display format, the cause shows not only the name of the class, (java.lang.ArithmeticException), from which the cause object was instantiated, but also displays the message, (/ by zero), that was encapsulated in the cause object when it was instantiated by the runtime system.
Throw another exception containing a cause
After getting and displaying the message and the cause, the code in the catch block in Listing 3 throws a new object of the class NewEx02, passing the RuntimeException object's reference as the cause parameter to the constructor.
(In this case, the cause was encapsulated in the object when the object was instantiated rather than encapsulating it later by invoking the initCause method on a reference to the object.)
This is a checked exception
Note that because NewEx02 extends Exception, making it a checked exception, the method named meth02 in Listing 3 must declare that it throws NewEx02.
Catch the exception
The exception thrown by the method named meth02 is caught by
the method named meth01, which is the next method up the call stack.
The method named meth01 is shown in Listing 4.
void meth01() throws NewEx01{ try{ meth02(); }//end try block catch(NewEx02 e){ System.out.println( "In meth01 catch block"); System.out.println( "Msg is:\n" + e.getMessage()); System.out.println( "Cause is:\n" + e.getCause()); System.out.println();//blank line throw new NewEx01( "Msg from meth01",e); }//end catch }//end meth01 Listing 4 |
Catch block is very similar
The code in the catch block in meth01 is very similar to that shown earlier for meth02. In particular, it begins by getting and displaying the message and the cause encapsulated in the incoming object of type NewEx02, know locally by the name e.
The output
The output produced by this code is similar to that shown in Figure
4. In this case, the cause is displayed as the combination
of the IndexOutOfBoundsException object and the message object encapsulated
in the NewEx02 object when it was instantiated and thrown.
In meth01 catch block Msg is: Msg from meth02 Cause is: java.lang.IndexOutOfBoundsException: Msg from metho03 Figure 4 |
Throw one more exception containing a cause
After displaying the message and the cause, the code in the catch block in Listing 4 instantiates and throws a new object of the class NewEx01. This object encapsulates a reference to the NewEx02 object received as an incoming parameter to the catch block as the cause object.
Again, because NewEx01 is a checked exception, the method named meth01 must declare that it can be thrown.
Catch the exception again
This exception is caught by the next method up the call stack, which
is the main method of the Excep20 class. The beginning
of the main method is shown in Listing 5.
public static void main( String[] args){ try{ new Class01().meth01(); }//end try catch(NewEx01 e){ System.out.println( "In main catch block"); System.out.println( "Msg is:\n" + e.getMessage()); System.out.println( "Cause is:\n" + e.getCause()); Listing 5 |
Get and display the message and the cause
As before, the code in Listing 5 gets and displays the message and the
cause
encapsulated in the incoming object to the catch block. By
now, there shouldn't be any surprises in the output produced by the code
in Listing 5. The output is similar to that shown in Figure 5.
In main catch block Msg is: Msg from meth01 Cause is: NewEx02: Msg from meth02 Figure 5 |
Now for something new
Listing 6 shows the remainder of the catch block in the main
method.
System.out.println( "Print StackTrace"); e.printStackTrace(); }//end catch Listing 6 |
Invoke the printStackTrace method
The code in Listing 6 invokes the upgraded printStackTrace method on the incoming parameter received by the catch block. This parameter is a reference to the object of type NewEx01, thrown by the method named meth01.
The printStackTrace method has been a part of Java for many years. However, it was upgraded in JDK 1.4 to support the cause facility. In particular, this method now produces a complete history of the chain of exceptions.
The output
The output produced by the invocation of the printStackTrace
method in Listing 6 is similar to that shown in Figure 6. (Again,
I had to manually insert some line breaks to cause the material to fit
in this narrow publication format.)
NewEx01: Msg from meth01 at Class01.meth01(Excep20.java:124) at Excep20.main(Excep20.java:61) Caused by: NewEx02: Msg from meth02 at Class01.meth02(Excep20.java:141) at Class01.meth01(Excep20.java:115) ... 1 more Caused by: java.lang.IndexOutOfBoundsException: Msg from metho03 at Class01.meth03(Excep20.java:151) at Class01.meth02(Excep20.java:132) ... 2 more Caused by: java.lang.ArithmeticException: / by zero at Class01.meth03(Excep20.java:149) ... 3 more Figure 6 |
The chain of exceptions
Starting at the bottom of Figure 6 and reading up, you can see that the chain begins with the innermost exception that was thrown. That exception was an ArithmeticException thrown by the runtime system when the code in meth03 attempted to perform an integer divide by zero operation on source code line number 149.
The chain ends with the exception of type NewEx01, thrown by the method named meth01, and caught by the main method.
The initCause method
Recall that the ArithmeticException was wrapped as the cause in an IndexOutOfBoundsException object, which is a legacy class that predates the release of JDK 1.4. The new initCause method was used to wrap the ArithmeticException object as the cause in the IndexOutOfBoundsException object.
Wrapping with a constructor
That IndexOutOfBoundsException object was wrapped as the cause in an exception object of type NewEx02. The NewEx02 class is a new class that provides constructors matching the new constructors of the Throwable class. The IndexOutOfBoundsException object was wrapped in the NewEx02 object when it was instantiated.
The NewEx02 object was in turn wrapped as the cause in an exception object of type NewEx01, when that object was instantiated. The cause was available to the catch block in the main method.
The complete causal history
The complete causal history is displayed in the stack trace of Figure 6. Prior to the release of JDK 1.4, there was no standard way to create and display a chain of exceptions as illustrated by Figure 6.
Programmatic access to stack trace information
In addition to the upgraded printStackTrace method illustrated in Figure 6, a new getStackTrace method was added in release 1.4, which provides programmatic access to the same stack trace information displayed by the printStackTrace method. This makes it possible for you to write code that can make decisions on the basis of information contained in the stack trace. I didn't demonstrate that capability in this lesson, but I hope to demonstrate it in a future lesson that deals heavily with matters involving the stack trace.
Remember, however, that you must be running Java version 1.4.0 or later to compile and execute this program.
/*File Excep20.java Copyright 2002, R. G. Baldwin Illustrates chained exceptions as supported by JDK 1.4.0 Tested using JDK 1.4.0 under Win2000 The output produced by the program is similar to the following: In meth02 catch block Msg is: Msg from metho03 Cause is: java.lang.ArithmeticException: / by zero In meth01 catch block Msg is: Msg from meth02 Cause is: java.lang.IndexOutOfBoundsException: Msg from metho03 In main catch block Msg is: Msg from meth01 Cause is: NewEx02: Msg from meth02 Print StackTrace NewEx01: Msg from meth01 at Class01.meth01(Excep20.java:124) at Excep20.main(Excep20.java:61) Caused by: NewEx02: Msg from meth02 at Class01.meth02(Excep20.java:141) at Class01.meth01(Excep20.java:115) ... 1 more Caused by: java.lang.IndexOutOfBoundsException: Msg from metho03 at Class01.meth03(Excep20.java:151) at Class01.meth02(Excep20.java:132) ... 2 more Caused by: java.lang.ArithmeticException: / by zero at Class01.meth03(Excep20.java:149) ... 3 more **************************************/ import java.io.*; class Excep20{ public static void main( String[] args){ try{ new Class01().meth01(); }catch(NewEx01 e){ System.out.println( "In main catch block"); System.out.println( "Msg is:\n" + e.getMessage()); System.out.println( "Cause is:\n" + e.getCause()); System.out.println();//blank line System.out.println( "Print StackTrace"); e.printStackTrace(); }//end catch }//end main }//end Excep20 //===================================// //This is a new exception class class NewEx01 extends Exception{ public NewEx01() { } public NewEx01(String message){ super(message); } public NewEx01(Throwable throwable){ super(throwable); } public NewEx01(String message, Throwable throwable){ super(message, throwable); } }//end NewEx01 //===================================// //This is a new exception class class NewEx02 extends Exception{ public NewEx02() { } public NewEx02(String message){ super(message); } public NewEx02(Throwable throwable){ super(throwable); } public NewEx02(String message, Throwable throwable){ super(message, throwable); } }//end NewEx02 //===================================// class Class01{ void meth01() throws NewEx01{ try{ meth02(); }catch(NewEx02 e){ System.out.println( "In meth01 catch block"); System.out.println( "Msg is:\n" + e.getMessage()); System.out.println( "Cause is:\n" + e.getCause()); System.out.println();//blank line throw new NewEx01( "Msg from meth01",e); }//end catch }//end meth01 //---------------------------------// void meth02() throws NewEx02{ try{ meth03(); }catch(RuntimeException e){ System.out.println( "In meth02 catch block"); System.out.println( "Msg is:\n" + e.getMessage()); System.out.println( "Cause is:\n" + e.getCause()); System.out.println(); throw new NewEx02( "Msg from meth02",e); }//end catch }//end meth02 //---------------------------------// void meth03(){ try{ int x = 3/0; }catch(ArithmeticException e){ IndexOutOfBoundsException ex = new IndexOutOfBoundsException( "Msg from metho03"); ex.initCause(e); throw ex; }//end catch }//end meth03 //---------------------------------// }//end Class01 Listing 7 |
Copyright 2002, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects, and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Programming Tutorials, which has gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-