Java Reference
In-Depth Information
can throw a general exception, you must either place a try-catch around the
invocation of that method or arrange to have the exception propagate up to the
calling method that invoked your method. If you want the exception to propa-
gate, then you must first declare that your method might throw the exception.
This declaration is made with the throws clause as the following code shows:
public void myMethod () throws NumberFormatException {
...
Integer.parseInt (str)
...
}
Here the myMethod() invokes the parseInt() method and, since it does not
use the try-catch to handle the exception, the method declaration includes
throws NumberFormatException in the method signature. You need do
nothing special when you call Integer.parseInt() . The JVM automatically
causes the exception to be propagated should one occur anywhere in your method.
Then the caller of your method must handle the exception.
In summary, whenever you call any method that might throw a checked excep-
tion, you must either put that method call into a try-catch block and handle the
exception yourself or declare that your method could throw the same exception.
(You can also declare that your method throws a superclass of the exception;
we discuss super- and subclasses in the next chapter.) If you do not use one
of these techniques to handle checked exceptions, the javac compiler returns
errors during compilation.
Run-time exceptions, unlike checked exceptions, do not have to be explicitly
handled in the source code. This avoids requiring that a try-catch be placed
around every integer divide operation, for example, to catch a possible divide
by zero or around every array variable to avoid indices going out of bounds.
However, you can handle possible run-time exceptions with try-catch if you
think there is a reasonable chance of one occurring.
(We discuss class inheritance in the next chapter but we note here that all
exceptions are instances of either the Exception class or its many subclasses.)
Note that you can use multiple catch clauses if the code can throw differ-
ent types of exceptions. For example, in this code we provide for two possible
Exception subclasses:
...
try {
... code...
} catch (NumberFormatException e) {
...
} catch (IOException e) {
Search WWH ::




Custom Search