Java Reference
In-Depth Information
Java provides the
try/catch/throw
mechanism for more sophisticated
error handling. It avoids a lot of unnecessary checking and passing on of errors.
The only parts of a Java program that need to deal with an error are those that
know what to do with it.
The
throw
in Java is really just a nonlocal “goto”—it will branch the exe-
cution of your program to a location which can be quite far away from the
method where the exception was thrown. But it does so in a very structured
and well-defined manner.
In our simple example of A calling B calling C calling D, D implemented
as a Java method can
throw
an exception when it runs into an error. Control
will pass to the first enclosing block of code on the call stack that contains a
catch
for that kind of exception. So A can have code that will
catch
an excep-
tion, and B and C need not have any error handling code at all. Example 3.17
demonstrates the syntax.
Example 3.17
A simple
try/catch
block
try {
for (i = 0; i < max; i++) {
someobj.methodB(param1, i);
}
} catch (Exception e) {
// do the error handling here:
System.out.println("Error encountered. Try again.");
}
// continues execution here after successful completion
// but also after the catch if an error occurs
In the example, if any of the calls to
methodB()
in the
for
loop go
awry—that is, anywhere inside
methodB()
or whatever methods it may call an
exception is thrown (and assuming those called methods don't have their own
try/catch
blocks), then control is passed up to the
catch
clause in our exam-
ple. The
for
loop is exited unfinished, and execution continues first with the
catch
clause and then with the statements after the
catch
.
How does an error get thrown in the first place? One simply creates an
Exception
object and then throws the exception (Example 3.18).