Java Reference
In-Depth Information
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
{
.
.
.
}
When an exception is thrown in a method but not caught in that method, that
immediately ends the method invocation.
Be sure to note that the throws clause for a method is for exceptions that “get out-
side” the method. If they do not get outside the method, they do not belong in the
throws clause. If they get outside the method, they belong in the throws clause no
matter where they originate. If an exception is thrown in a try block that is inside a
method definition and is caught in a catch block inside the method definition, then
its exception class need not be listed in the throws clause. If a method definition
includes an invocation of another method and that other method can throw an excep-
tion that is not caught, then the exception class of that exception should be placed in
the throws clause.
Throwing an Exception Can End a Method
If a method throws an exception, and the exception is not caught inside the method, then
the method invocation ends immediately after the exception is thrown.
In Display 9.9, we have rewritten the program from Display 9.4 so that the exception
is thrown in the method safeDivide . The method main includes a call to the method
safeDivide and puts the call in a try block. Because the method safeDivide can throw
a DivisionByZeroException that is not caught in the method safeDivide , we needed to
declare this in a throws clause at the start of the definition of safeDivide . If we set up
Search WWH ::




Custom Search