Java Reference
In-Depth Information
Java syntax: throws-clause
throws class-name , …, class-name
Example : throws ArithmeticException
Purpose : Placed in the header of a method, the throws-clause indicates that the
method may throw objects of the given class-name s and relieves the method of
the responsibility of catching them —that responsibility is passed to methods that
call this method. The throws-clause is needed for “checked Exceptions”.
first() throws ob .
The call to method first is within a try-block, so if one of its catch claus-
es catches ob , that ends the throwing. But, if the catch clauses do not catch ob .
Then ob is thrown outside the try-statement, so that it looks like the try-statement
throws the object. In our example, the try-statement is not in a try-block, so ob
is thrown to the caller of method main , which is within the Java system.
The call of method main within the system is within the try-block of a try-
statement that catches all Throwable objects, and its catch-block is guaranteed
to print the information about ob .
The general rules for throwing an object
We have shown with an example how an object is thrown. We now give a
more formal description of throwing an object ob . The following cases can arise:
1. Object ob was thrown in a try-block and is caught by a catch clause. That
catch clause processes ob .
2. Object ob was thrown in a try-block and is not caught by a catch clause.
Then ob is thrown out to the try-statement —it is as if the try-statement
itself threw ob .
3. Object ob was thrown by a statement that is not within a try-block. This
statement occurs within a method body that is being executed for some
method call. Then ob is thrown out to that call —it is as if the method call
threw ob .
This process is repeated over and over until ob is caught. If the program does
not catch ob , it will be caught by the Java system: the call that started execution
of the program is within a try-statement that catches all thrown objects.
Throwing an object while another is being handled or propagated
Nothing prevents a catch-block from throwing another object a1 (say) —by
mistake or otherwise— while a previously thrown object a0 is being handled. If
this happens, the previously thrown object a0 is ignored and the newly thrown
object a1 is propagated, as described earlier.
To test this yourself, place the method of Fig. 10.8 into a Java program, exe-
cute it, and compare the output messages with the method.
Search WWH ::

Custom Search