<< Chapter < Page | Chapter >> Page > |
Throwing an ArithmeticException
The code in Listing 4 executes a simple counting loop inside a try block. During each iteration, the counting loop divides the integer 6 by thevalue of the counter. When the value of the counter goes to zero, the runtime system tries to perform an integer divide by zero operation, which causes it tothrow an ArithmeticException .
Transfer control immediately
At that point, control is transferred directly to the catch block that follows the try block. This is an appropriate catch block because the type of parameter declared for the catch block is ArithmeticException . It matches the type of the object that is thrown.
(It would also be appropriate if the declared type of the parameter were a superclass of ArithmeticException , up to and including the class named Throwable . Throwable is a direct subclass of Object . If you were to declare the parameter type for the catch block as Object , the compiler would produce an incompatible type error.)
Calling methods inside the catch block
Once control enters the catch block, three of the methods of the Throwable class are called to cause information about the situation to be displayed on the screen.The output produced by the program is similar to that shown in Figure 5 .
Figure 5 . Output from program that throws ArithmeticException. |
---|
Running. Quotient is: 3
Running. Quotient is: 6Exception message is: / by zero
Stacktrace shows:java.lang.ArithmeticException:
/ by zeroat Excep14.main(Excep14.java:35)
String representation isjava.lang.ArithmeticException:
/ by zeroPut corrective action here
Out of catch block |
Key things to note
The key things to note about the code in Listing 4 and the output in Figure 5 are:
Doesn't attempt to rectify the problem
This program doesn't attempt to show how an actual program might recover from an exception of this sort. However, it is clear that (rather than experiencing automatic and unconditional termination) the program remains in control, and in some cases, recovery might be possible.
This sample program illustrates try and catch . The use of finally , will be discussed and illustrated later.
A nuisance problem explained
While we are at it, I would be remiss in failing to mention a nuisance problem associated with exception handling.
As you may recall, the scope of a variable in Java is limited to the block of code in which it is declared. A block is determined by enclosing code within apair of matching curly brackets: {...}.
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?