Java Reference
In-Depth Information
Example 3.18
Throwing an
Exception
, step by step
Exception ex = new Exception("Bad News");
throw ex;
Since there is little point in keeping the reference to the object for the local
method—execution is about to leave the local method—there is no need to
declare a local variable to hold the exception. Instead, we can create the excep-
tion and throw it all in one step (Example 3.19).
Example 3.19
Throwing an
Exception
, one step
throw new Exception("Bad News");
Exception
is an object, and as such it can be extended. So we can create
our own unique kinds of exceptions to differentiate all sorts of error conditions.
Moreover, as objects, exceptions can contain any data that we might want to
pass back to the calling methods to provide better diagnosis and recovery.
The
try/catch
block can catch different kinds of exceptions much
like cases in a
switch/case
statement, though with different syntax
(Example 3.20).
Notice that each
catch
has to declare the type of each exception and
provide a local variable to hold a reference to that exception. Then method calls
can be made on that exception or references to any of its publicly available data
can be made.
Remember how we created an exception (
new Exception("message")
)?
That message can be retrieved from the exception with the
toString()
method, as shown in that example. The method
printStackTrace()
is also
available to print out the sequence of method calls that led up to the creation
of the exception (Example 3.21).
The exception's stack trace is read top to bottom showing the most
recently called module first. Our example shows that the exception occurred
(i.e., was constructed) on line 6 of the class named
InnerMost
, inside a method
named
doOtherStuff()
. The
doOtherStuff()
method was called from
inside the class
MidModule
—on line 7—in a method named
doStuff()
.
In turn,
doStuff()
had been called by
doSomething()
, at line 11 inside