Exceptions
3. Catching and propagating thrown objects
The try statement
Java provides a statement, the try-statement, that allows your program to catch a thrown exception and handle it in some fashion. This means that your program need not terminate when a certain exception is thrown; instead, it can catch it and handle it. This exception handling mechanism will be disconcerting at first, because it changes the normal flow of execution. Click the icon to the left to see a 4.5 minute video on this topic. Here's the modified script.
The use of the try-statement shown is not very realistic. Generally, our
program shouldn't even try to divide by
Using the try-statement to return a value in an array
This 4-minute video looks at method getIntField, which returns a value in a string array, changed into an int. Two different exceptions are caught and handled in this method: a subscript is out of bounds and the array element does not contain an integer. This video talks about the method being in a class JLiveWindow. You don't need to know anything about that class. Here's the modified script. The code: JLiveWindow.zip
Using the try-statement to read from the keyboard
This 2.5 minute video looks at method
In the above video, method Integer.intValue threw the exception if the argument was not a string that contained an integer. method intValue does not know how to handle the exception, but readLineInt does. This is a neat example of Java's exception-handling mechanism.
Propagation of a thrown object
This 2.5 minute video shows what happens if a thrown object is not caught by a catch block.
The thrown object is thrown out to where the method (in which the exception was thrown) was called, and it looks like the method call threw the object. And, if that call is not caught by a catch block, it throws the object out to the place where it was called. And so it goes. Here's the modified script.
Catching all exceptions
Here's an interesting point. You can catch all Exceptions by using a catch clause of the form:
catch (Exception ex) { ... }
Though we don't recommend it, you can even catch all throwable objects using a catch clause of the form:
catch (Throwable th) { ... }
The finally-clause
A try-statement can have a finally-clause:
try <try-block>
<catch clause>
...
<catch clause>
finally <finally-block>
If a
©This material is from the CD ProgramLive by David Gries and Paul Gries