Java Reference
In-Depth Information
Figure 11.7
Output of the HandleOrDeclare program when a FileNotFoundException occurs.
Try to determine the output of the HandleOrDeclare program, both when an
exception occurs and when no exception occurs. An example of the output
when an exception occurs is shown in Figure 11.7. Study the output carefully
and follow the flow of control.
Throwing Exceptions
You can throw an exception, either a newly instantiated one or an exception
that you just caught, by using the throw keyword. A throw statement causes
the current method to immediately stop executing, much like a return state-
ment, and the exception is thrown to the previous method on the call stack.
For example, the following statement throws a new ArrayIndexOutOf-
BoundsException, with 5 being the invalid index:
throw new ArrayIndexOutOfBoundsException(5);
You can also instantiate an exception object and then throw it in a separate
statement:
ArrayIndexOutOfBoundsException a =
new ArrayIndexOutOfBoundsException(5);
//Some time later
throw a;
You can throw only objects of type java.lang.Throwable. In almost all
situations, you will throw an object that is a child of java.lang.Exception.
Recall that the Exception class extends the Throwable class.
Search WWH ::




Custom Search