Java Reference
In-Depth Information
Catching and throwing an Exception further
Figure 10.1 contains method
mod
. Its first statement throws an exception if
y = 0
. We wrote the function this way so that we could give our own detail mes-
sage. But there is another way to get the same result, as shown in Fig. 10.9.
We remove the if-statement and place the whole body in a try-statement that
catches
ArithmeticException
s. Then, in the catch-block, we throw a new
exception with the desired message. The new method body does not rethrow
object
ae
; instead, it creates a new object and throws it. This is done because it
is not possible to change the detail message of a throwable object.
But there are cases where rethrowing
ae
makes sense. For example, one
might catch the exception only to dispose of some resources
—
which is beyond
the scope of this text— and then rethrow the same exception.
This second way of detecting that
y
is
0
is more in keeping with the excep-
tion-mechanism philosophy. Rather than intersperse lots of tests for errors, which
might double the size of the code, let the exception-handling facilities do that
work. Of course, in this case, this second way yields a longer program, but in
general, using the exception-handling facilities can help.
Activity
10-4.2
Get function
mod2 of Fig.
10.8 from a
footnote on les-
son page 10-2.
10.5
Checked Exceptions
A Java compiler checks to make sure that certain thrown objects are caught by
your program; if they are not caught, the compiler issues an error message and
refuses to compile the program. For example, consider this silly program:
Lesson
page 10-5
public class
C {
public static void
main(String[] args)
{ first(); }
public static void
first()
{
throw new
Exception(); }
}
Method
first
may throw an
Exception
but does not catch it, and this makes the
public static void
main(String[] args) {
try
{
System.out.println("try-block 0 ");
throw new
ArithmeticException("fake exception 1 ");
}
catch
(ArithmeticException ae) {
System.out.println("catch-block 0 ");
System.out.println(ae);
throw new
ArithmeticException("fake exception 2 ");
}
}
Figure 10.8:
A catch-block itself can throw an exception
Search WWH ::
Custom Search