Java Reference
In-Depth Information
Exception Consistency Checking
The more you work with the Java class libraries, the more likely you'll run into a com-
piler error (an exception!) such as this one:
XMLParser.java:32: Exception java.lang.InterruptedException
must be caught or it must be declared in the throws clause
of this method.
In Java, a method can indicate the kinds of errors it might potentially throw. For exam-
ple, methods that read from files can throw IOException errors, so those methods are
declared with a special modifier that indicates potential errors. When you use those
methods in your own Java programs, you have to protect your code against those excep-
tions. This rule is enforced by the compiler itself, in the same way that it checks to make
sure that you're using methods with the correct number of arguments and that all your
variable types match what you're assigning to them.
Why is this check in place? It makes your programs less likely to crash with fatal errors
because you know up front the kind of exceptions that can be thrown by the methods a
program uses.
You no longer have to pore over the documentation or the code of an object you're going
to use to ensure that you've dealt with all the potential problems—Java does the check-
ing for you. On the other side, if you define your methods so that they indicate the
exceptions they can throw, Java can tell your objects' users to handle those errors.
Protecting Code and Catching Exceptions
Assume that you've been happily coding and the compiler screeches to a halt with an
exception as a class is compiled. According to the message, you have to either catch the
error or declare that your method throws it.
First, we'll deal with catching potential exceptions, which requires two things:
You protect the code that contains the method that might throw an exception inside
a try block.
n
You deal with an exception inside a catch block.
n
What try and catch effectively mean is: “Try this bit of code that might cause an excep-
tion. If it executes okay, go on with the program. If the code doesn't execute, catch the
exception and deal with it.”
Search WWH ::




Custom Search