Now we can rewrite the accelerate() method of Automobile as follows:
public void accelerate ( double newSpeed )
throws ExcessiveSpeedException {
if( newSpeed > 70. )
throw new ExcessiveSpeedException( this );
speed = newSpeed;
}
The reference to this means that the particular instance of Automobile that generates the
ExcessiveSpeedException will be passed to the ExcessiveSpeedException constructor. Notice
that the method header for accelerate() now includes a declaration that the method can throw an
ExcessiveSpeedException. If you forget to include the declaration, the compiler will require such a
declaration when it sees that some statement within the method throws an ExcessiveSpeedException.
Finally, notice that we no longer require an else clause after the if statement. Once a method throws an
exception, execution stops, except for whatever code is ready to catch the Exception. Therefore, we no
longer need else to insure two non-overlapping paths of execution in response to the test in the if statement.
We can rewrite the AutomobileFactory class to handle the possible occurrence of an
ExcessiveSpeedException.
.
.
.
try {
family.accelerate( 120. );
sports.accelerate( 120. );
}
catch( ExcessiveSpeedException ex) {
System.
Pages:
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235