Java Reference
In-Depth Information
Most “ordinary” exceptions that might be thrown when a method is invoked must
be accounted for in one of two ways:
• The possible exception can be caught in a
catch
block within the method definition.
• 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 the first technique, handling exceptions in a
catch
block.
The second technique 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 exceptions
of type
DivisionByZeroException
that might occur when
yourMethod
is executed.
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
DivisionByZeroException
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.
throws
Clause
If you define a method that might throw exceptions of some particular class, then normally
either your method definition must include a
catch
block that will catch the exception or
you must declare (that is, list) the exception class within a
throws
clause, as described in
what follows.
SYNTAX (COVERS MOST COMMON CASES)
public
Type_Or_void Method
(
Parameter_List
)
throws
List_Of_Exceptions
Body_Of_Method
EXAMPLE
public void
yourMethod(
int
n)
throws
MyException, YourException
{
.
.
.
}