Java Reference
In-Depth Information
Declaring Exceptions in a throws Clause
If a method does not catch an exception, then (in most cases) it must at least warn
programmers that any invocation of the method might possibly throw an exception.
This warning is called a throws clause, and including an exception class in a throws
clause is called declaring the exception . For example, a method that might possibly
throw a DivisionByZeroException and that does not catch the exception would have
a heading similar to the following:
throws clause
declaring an
exception
public void sampleMethod() throws DivisionByZeroException
The part throws DivisionByZeroException is a throws clause stating that an invoca-
tion of the method sampleMethod might throw a DivisionByZeroException .
If there is more than one possible exception that can be thrown in the method defi-
nition, then the exception types are separated by commas, as illustrated in what follows:
throws clause
public void sampleMethod()
throws DivisionByZeroException, SomeOtherException
Most “ordinary” exceptions that might be thrown when a method is invoked must
be accounted for in one of two ways:
1. The possible exception can be caught in a catch block within the method definition.
2. The possible exception can be declared at the start of the method definition by
placing the exception class name in a throws clause (and letting whoever uses the
method worry about how to handle the exception).
This is often called the Catch or Declare Rule . In any one method, you can mix the
two alternatives, catching some exceptions and declaring others in a throws clause.
You already know about technique 1, handling exceptions in a catch block. Tech-
nique 2 is a form of shifting responsibility (“passing the buck”). For example, suppose
yourMethod has a throws clause as follows:
Catch or
Declare Rule
public void yourMethod() throws DivisionByZeroException
In this case, yourMethod is absolved of the responsibility of catching any excep-
tions of type DivisionByZeroException that might occur when yourMethod is exe-
cuted. If, however, there is another method, myMethod , that includes an invocation
of yourMethod , then myMethod must handle the exception. When you add a throws
clause to yourMethod , you are saying to myMethod , “If you invoke yourMethod , you
must handle any DivisionByZeroException that is thrown.” In effect, yourMethod
has passed the responsibility for any exceptions of type DivisionByZeroException
from itself to any method that calls it.
Of course, if yourMethod passes responsibility to myMethod by including Division-
ByZeroException in a throws clause, then myMethod may also pass the responsibility to
whoever calls it by including the same throws clause in its definition. But in a well-
written program, every exception that is thrown should eventually be caught by a catch
block in some method that does not just declare the exception class in a throws clause.
Search WWH ::




Custom Search