Java Reference
In-Depth Information
A finally block is used to contain code that must be executed after the execution of a try
block, regardless of how the try block execution ends. A finally block will always be
executed before execution of the method ends.
You can throw an exception by using a throw statement. You can throw an exception
anywhere in a method. You can also rethrow an existing exception in a catch block to pass it
to the calling method.
You can define your own exception classes that, in general, should be derived from the class
Exception .
Exercises
1. Write a program that will generate exceptions of type NullPointerException ,
NegativeArraySizeException , and IndexOutOfBoundsException . Record the
catching of each exception by displaying the message stored in the exception object, and the
stack trace record.
2.
Add an exception class to the last example that will differentiate between the index-out-of-
bounds error possibilities, rethrow an appropriate object of this exception class in divide() ,
and handle the exception in main() .
3.
Write a program that calls a method which throws an exception of type
ArithmeticException at a random iteration in a for loop. Catch the exception in the
method, and pass the iteration count when the exception occurred to the calling method, by
using an object of an exception class you define.
4.
Add a finally block to the method in the previous example to output the iteration count
when the method exits.
Search WWH ::




Custom Search