Java Reference
In-Depth Information
double ( int aParam)
throws , {
doSomething
ExceptionType1 ExceptionType2
try{
//Code that does throw exceptions
//Code that does not throw exceptions
}
//Set of try/catch/finally blocks...
catch( e){
//Code to process exception
MyException1
//Code that does not throw exceptions
}
Typical
Structure
//Set of try/catch/finally blocks...
catch( e){
//Code to process exception
MyException2
//Code that does not throw exceptions
}
//Set of try/catch/finally blocks...
finally{
//Code to execute after the try block
//Code that does not throw exceptions
}
//...
In general there can be as many
blocks as required, and there may be none.
catch
}
The
block is optional if there is a
block
finally
catch
In many cases, a method will only need a single try block followed by all the catch blocks for the
exceptions that need to be processed in the method, perhaps followed by a finally block. Java,
however, gives you the flexibility to have as many try blocks as you want. This makes it possible for
you to separate various operations in a method by putting each of them in their own try block - an
exception thrown as a result of a problem with one operation does not prevent subsequent operations
from being executed.
The throws clause that follows the parameter list for the method identifies exceptions that can be
thrown in this method, but which aren't caught by any of the catch blocks within the method. We saw
this earlier in this chapter. Exceptions that aren't caught can be thrown by code anywhere in the body
of the method - in code not enclosed by a try block.
Execution Sequence
We saw how the sequence of execution proceeded with the simple case of a try block and a single catch
block. We also need to understand the sequence in which code is executed when we have the try-catch-
finally combinations of blocks, when different exceptions are thrown. This is easiest to comprehend by
considering an example. We can use the following code to create a range of exceptions and conditions.
Try It Out - Execution Sequence of a try Block
It will be convenient, in this example, to use an input statement to pause the program. The method we
will use can throw an exception of a type defined in the java.io package. We will start by importing
the java.io.IOException class into the source file. We will give the class containing main() the
name TryBlockTest , and we will define another method, divide() , in this class that will be called
in main() . The overall structure of the TryBlockTest class source file will be:
import java.io.IOException;
public class TryBlockTest {
Search WWH ::




Custom Search