Java Reference
In-Depth Information
10.4
Catching a thrown Exception
10.4.1
The try-statement
The program segment below contains a try-statement :
Activity
10-3.1
Calculate x;
try {
y= 5 / x;
} catch (ArithmeticException ae) {
System.out.println("x was 0; using 0 for 5 / x");
y= 0;
}
third statement
The second is a try-statement , of the form:
try {
try-block
} catch ( parameter-declaration ) {
catch-block
}
The parameter-declaration must declare an object of some throwable class. In the
try-block above, parameter ae is ArithmeticException , a throwable class.
Execution of the try-statement begins with execution of the try-block. We
have three cases to consider, depending on whether an object is thrown and, if
one is thrown, whether this try-statement catches it.
1. If no object is thrown, execution of the try-statement terminates when
execution of the try-block does. This is the usual case.
2. If some object ob is thrown, the try-block is abnormally terminated. What
happens next depends on the catch clause that follows the try-block.
2a. If the class of the catch-clause parameter matches the class of instance
/** Thrown when an exceptional arithmetic condition has occurred. For example, an integer
"divide by zero" throws an instance of this class. */
public class ArithmeticException extends RuntimeException {
/** Constructor: an instance with no detail message */
public ArithmeticException()
{ super (); }
/** Constructor: an instance with detail message s */
public ArithmeticException(String s)
{ super (s); }
}
Figure 10.5:
Class ArithmeticException
Search WWH ::




Custom Search