Java Reference
In-Depth Information
This will produce the output:
Try block entered i = 12 j = 3
4
Ending try block
Try block entered i = 12 j = 2
6
Ending try block
Try block entered i = 12 j = 1
12
Ending try block
Try block entered i = 12 j = 0
Arithmetic exception caught
Try block entered i = 12 j = -1
-12
Ending try block
After try block
How It Works
The try and catch blocks are all part of the loop since the catch is inextricably bound to the try .
You can see this from the output. On the fourth iteration, we get an exception thrown because j is 0.
However, after the catch block is executed, we still get one more iteration with j having the value -1.
Even though both the try and catch blocks are within the for loop, they have separate scopes.
Variables declared within the try block cease to exist when an exception is thrown. You can
demonstrate that this is so by declaring an arbitrary variable, k say, in the try block, and then adding
a statement to output k in the catch block. Your code will not compile in this case.
Suppose you wanted the loop to end when an exception was thrown. You can easily arrange for this.
Just put the whole loop in a try block, thus:
public static void main(String[] args) {
int i = 12;
try {
System.out.println("Try block entered.");
for(int j=3 ;j>=-1 ; j--) {
System.out.println("Loop 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;
}
With this version of main() , the previous program will produce the output:
Search WWH ::




Custom Search