Java Reference
In-Depth Information
The
try
and
catch
blocks are all part of the loop because the
catch
is inextricably bound to the
try
.
You can see this from the output. On the fourth iteration, you get an exception thrown because
j
is 0.
However, after the
catch
block is executed, you still get one more iteration with
j
having the value −1.
Even though the
try
and
catch
blocks are both 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 does 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("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: " + e);
}
System.out.println("After try block");
}
TestLoopTryCatch2.java
With this version of
main()
, the program produces the following output:
Try block entered.
Try block entered i = 12 j = 3
4
Try block entered i = 12 j = 2
6
Try block entered i = 12 j = 1
12
Try block entered i = 12 j = 0
Arithmetic exception caught: java.lang.ArithmeticException: / by zero
After try block
Now, you no longer get the output for the last iteration because control passes to the
catch
block when
the exception is thrown, and that is now outside the loop.