Java Reference
In-Depth Information
Try block entered i = 1 j = 1
1
Ending try block
After try block
From this you can see that the entire
try
block is executed. Execution then continues with the
statement after the
catch
block. Because no arithmetic exception was thrown, the code in the
catch
block isn't executed.
You need to take care when adding
try
blocks to existing code. A
try
block is no
different to any other block between braces when it comes to variable scope. Variables
declared in a
try
block are only available until the closing brace for the block. It's
easy to enclose the declaration of a variable in a
try
block, and, in doing so,
inadvertently limit the scope of the variable and cause compiler errors.
The
catch
block itself is a separate scope from the
try
block. If you want the catch block to output
information about objects or values that are set in the
try
block, make sure the variables are declared
in an outer scope.
try catch Bonding
The
try
and
catch
blocks are bonded together. You must not separate them by putting statements
between the two blocks, or even by putting braces around the
try
keyword and the
try
block itself. If
you have a loop block that is also a
try
block, the
catch
block that follows is also part of the loop. We
can see this with a variation of the previous example.
Try It Out - A Loop Block That is a
try
Block
We can make
j
a loop control variable and count down so that eventually we get a zero divisor in the loop:
public class TestLoopTryCatch {
public static void main(String[] args) {
int i = 12;
for(int j=3 ;j>=-1 ; j--) {
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;
}
}