Java Reference
In-Depth Information
if (Math.random() < 0.1)
throw
new
PressureException("pressure
too
high");
else
if (Math.random() > 0.9)
throw
new
TemperatureException("temperature
too high");
else
System.out.println("all is well");
}
catch (Exception e)
{
System.out.println(e.getMessage());
throw e;
}
}
}
Listing 3-27
simulates the testing of an experimental rocket engine to see if the en-
gine'spressureortemperatureexceedsasafetythreshold.Itperformsthistestingviathe
monitor()
helper method.
monitor()
'stryblockthrows
PressureException
whenitdetectsapressure
extreme, and throws
TemperatureException
when it detects a temperature ex-
treme.(Becausethisisonlyasimulation,randomumbersareused.I'llhavemoretosay
aboutrandomumbersin
Chapter4
.)Thetryblockisfollowedbyacatchblock,which
is designed to partly handle the exception by outputting a warning message. This ex-
ception is then rethrown so that
monitor()
's calling method can finish handling the
exception.
Before Java 7, you couldn't specify
PressureException
and
Temperat-
ureException
in
monitor()
'sthrowsclausebecausethecatchblock's
e
paramet-
erisoftype
Exception
andrethrowinganexceptionwastreatedasthrowingthepara-
meter's type.Starting withJava7,youcanspecifytheseexception typesinthethrows
clause because the compiler determines that the exception thrown by
throw e
came
from the try block, and only
PressureException
and
TemperatureExcep-
tion
can be thrown from this block.