Download Java Programming/Print version - Computer Science & Engineering
Transcript
Catching an exception
30.2 Catching an exception
To see how an exception is caught, you must first understand the concept of a guarded region.
This is a section of code that might produce exceptions and is followed by the code to handle
those exceptions.
30.2.1 The try block
If you are inside a method and you throw an exception (or another method that you call within
this method throws an exception), that method will exit in the process of throwing. If you don’t
want a throw to exit the method, you can set up a special block within that method to capture
the exception. This is called the try block because you "try" your various method calls there. The
try block is an ordinary scope preceded by the keyword try.
Listing 1.5: A basic try block.
try
{
// Code that might generate exceptions
}
If you were checking for errors carefully in a programming language that didn’t support exception handling, you’d have to surround every method call with setup and error-testing code, even
if you call the same method several times. With exception handling, you put everything in a try
block and capture all the exceptions in one place. This means your code is much easier to write
and read because the goal of the code is not confused with the error checking.
30.3 Exception handlers
Of course, the thrown exception must end up some place. This "place" is the exception handler,
and there’s one for every exception type you want to catch. Exception handlers immediately
follow the try block and are denoted by the keyword catch:
Listing 1.6: Exception handling with catch blocks.
try
{
// Suppose the code here throws two exceptions:
// NullPointerException and NumberFormatException,
// then each is handled in a separate catch block.
}
catch(NullPointerException ex)
{
// Exception handling code for the NullPointerException
}
catch(NumberFormatException ex)
{
// Exception handling code for the NumberFormatException
}
// etc...
Using the syntax in Listing 1.6, we can write the potentially problematic division code in Listing
1.1 as under.
165