Java Reference
In-Depth Information
In general, the parameter for a catch block must be of type Throwable or one of the subclasses of the
class Throwable . If the class that you specify as the parameter type has subclasses, the catch block
will be expected to process exceptions of that class, plus all subclasses of the class. If you specified the
parameter to a catch block as type RuntimeException for example, the code in the catch block
would be invoked for exceptions defined by the class RuntimeException , or any of its subclasses.
We can see how this works with a simple example. It doesn't matter what the code does - the important
thing is that it throws an exception we can catch.
Try It Out - Using a try and a catch Block
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");
return;
}
}
If you run the example, you should get the output:
Try block entered i = 1 j = 0
Arithmetic exception caught
After try block
How It Works
The variable j is initialized to 0, so that the divide operation in the try block will throw an
ArithmeticException exception. We must use the variable j with the value 0 here because the Java
compiler will not allow you to explicitly divide by zero - that is, the expression i/0 will not compile.
The first line in the try block will enable us to track when the try block is entered, and the second
line will throw an exception. The third line can only be executed if the exception isn't thrown - which
can't occur in this example.
This shows that when the exception is thrown, control transfers immediately to the first statement in the
catch block. It's the evaluation of the expression that is the argument to the println() method that
throws the exception, so the println() method never gets called. After the catch block has been
executed, execution then continues with the statement following the catch block. The statements in the try
block following the point where the exception occurred aren't executed. You could try running the example
again after changing the value of j to 1 so that no exception is thrown. The output in this case will be:
Search WWH ::




Custom Search