4. The throw-statement
The throw-statement can be used to throw an object when a program detects an error. The use of the throw-statement allows a program to react to errors that it detects just the way the Java runtime system and all the predefined classes react. This allows a certain uniformity that would not be possible otherwise. Click the icon to see how to throw an exception! Here's the modified script.
The throw-statement has the form:
throw <expression> ;
where the expression yields an instance of (a subclass of)
Throwing an object while another is being handled or propagated
Nothing prevents a catch-block or finally-block from
throwing another object
Try this out yourself. Write a method
public static void main(String[] pars) {
try {
System.out.println("try-block 0");
throw new ArithmeticException("fake exception 1");
} catch (ArithmeticException ae) {
System.out.println("catch-block 0");
System.out.println(ae);
throw new ArithmeticException("fake exception 2");
}
}
Catching and throwing an exception further
See why it may be useful to catch an
©This material is from the CD ProgramLive by David Gries and Paul Gries