Java Reference
In-Depth Information
As the preceding fragment illustrates, to declare that your method can throw exceptions you just put the
throws keyword after the parameter list for the method. Then add the list of classes for the exceptions that
might be thrown, separated by commas. This propagates — if another method calls this method, it too must
take account of the exceptions this method can throw. The calling method definition must either deal with
the exceptions or declare that it can throw these exceptions as well. It's a simple choice. You either pass the
buck or decide that the buck stops here. The compiler checks for this and your code does not compile if you
don't do one or the other. The reasons for this become obvious when you look at the way a Java program
behaves when it encounters an exception.
Handling Exceptions
If you want to deal with checked exceptions where they occur, you can include three kinds of code blocks
in a method to handle them — try , catch , and finally blocks:
• A try block encloses code that may give rise to one or more exceptions. Code that can throw an
exception that you want to catch must be in a try block.
• A catch block encloses code that is intended to handle exceptions of a particular type that may be
thrown in the associated try block. I get to how a catch block is associated with a try block later
in this chapter.
• The code in a finally block is always executed before the method ends, regardless of whether
any exceptions are thrown in the try block.
Let's dig into the detail of try and catch blocks first and then come back to the application of a finally
block a little later.
The try Block
You can do something about many of the exceptions that are thrown. In the last two chapters you'll be work-
ing with XML documents where exceptions are thrown to indicate errors in the XML. You will usually want
to catch these and report the location of an error in the document. When you want to catch an exception,
the code in the method that might cause the exception to be thrown must be enclosed in a try block. Code
that can cause exceptions need not be in a try block, but in this case, the method containing the code won't
be able to catch any exceptions that are thrown and the method must declare that it can throw the types of
exceptions that are not caught.
A try block is simply the keyword try , followed by braces enclosing the code that can throw the excep-
tion:
try {
// Code that can throw one or more exceptions
}
Although I am discussing primarily exceptions that you must deal with here, a try block is also necessary
if you want to catch exceptions of type Error or RuntimeException . When you come to a working example
in a moment, you use an exception type that you don't have to catch, simply because exceptions of this type
are easy to generate.
The catch Block
Search WWH ::




Custom Search