Java Reference
In-Depth Information
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 causes an
ArithmeticEx-
ception
exception to be thrown by the Java Virtual Machine. The first line in the
try
block enables you
to track when the
try
block is entered, and the second line throws an exception. The third line can be
executed only if the exception isn't thrown — which can't occur in this example.
The output 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
is:
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.
WARNING
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 available only 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. You can see this
with a variation of the previous example.