Java Reference
In-Depth Information
You enclose the code to handle an exception of a given type in a catch block. The catch block must imme-
diately follow the try block that contains the code that may throw that particular exception. A catch block
consists of the keyword catch followed by a single parameter between parentheses. The parameter identi-
fies the type of exception that the block is to deal with. This is followed by the code to handle the exception
enclosed between braces:
try {
// Code that can throw one or more exceptions
} catch(IOException e) {
// Code to handle the exception
}
This catch block handles exceptions of type IOException or of any subclass of IOException . If other
checked exceptions can be thrown that are not declared in the method signature, this won't compile. I'll
come back to handling multiple exception types in a moment.
TRY IT OUT: Using a try and a catch Block
This example throws an unchecked exception. I chose to do this rather that an example throwing checked
exceptions because the condition for an ArithmeticException to be thrown is very easy to generate.
The following code is really just an exhaustive log of the program's execution:
public class TestTryCatch {
public static void main(String[] args) {
int i = 1;
int j = 0;
try {
System.out.println("Try block entered " + "i = "+ i + " j =
"+j);
System.out.println(i/j);
// Divide by 0 -
exception thrown
System.out.println("Ending try block");
} catch(ArithmeticException e) { // Catch the exception
System.out.println("Arithmetic exception caught");
}
System.out.println("After try block");
}
}
TestTryCatch.java
If you run the example, you should get the following output:
Search WWH ::




Custom Search