The way to add exception handling to a Java program is to enclose program statements which might generate
an Exception within a try block. A try block begins with the key word try and an open curly brace.
At the end of the code being included in the try block is a close curly brace. Immediately following the try block
will be one or more catch blocks. A catch block contains the code to handle the error.
Let??™s go back to our Automobile class and its accelerate() method. Instead of simply setting the
speed of the Automobile to its maximum value when the argument to the accelerate() method is too
large, we can have the Automobile class generate a special subclass of Exception appropriate to this
application. Here is the code for our new ExcessiveSpeedException class:
CHAP. 5] PROGRAMMING IN JAVA 85
public class ExcessiveSpeedException extends Exception {
ExcessiveSpeedException( Automobile a ) {
super( "New speed exceeds maximum speed of "
+ a.toString() );
}
}
Our ExcessiveSpeedException inherits from Exception. The ExcessiveSpeedException
constructor expects an Automobile object as an argument. To take advantage of the message attribute inherited
from the superior class, it incorporates the toString() description of the Automobile into the message
that it passes to the constructor of the superior Exception class.
Pages:
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234