Java Reference
In-Depth Information
try
{
int x = 1/0;
}
catch (ArithmeticException ae)
{
System.out.println("attempt to divide by zero");
}
Whenexecutionentersthetryblock,anattemptismadetodivideinteger1byinteger
0. The JVM responds by instantiating ArithmeticException and throwing this
exception.Itthendetectsthecatchblock,whichiscapableofhandlingthrown Arith-
meticException objects,andtransfersexecutiontothisblock,whichinvokes Sys-
tem.out.println() to output a suitable message—the exception is handled.
Because ArithmeticException isanexampleofanuncheckedexceptiontype,
and because unchecked exceptions represent coding mistakes that must be fixed, you
typicallydon'tcatchthem,asdemonstratedpreviously.Instead,youwouldfixtheprob-
lem that led to the thrown exception.
Tip Youmightwanttonameyourcatchblockparametersusingtheabbreviatedstyle
shownintheprecedingsection.notonlydoesthisconventionresultinmoremeaningful
exception-oriented parameter names ( ae implies that an ArithmeticException
object has been thrown), it can help reduce compiler errors. For example, it is com-
monpracticetonameacatchblock'sparameter e ,forconvenience.(Whytypealong
name?) However, the compiler will report an error when a previously declared local
variable or parameter also uses e as its name—multiple same-named local variables
and parameters cannot exist in the same scope.
Handling Multiple Exception Types
You can specify multiple catch blocks after a try block. For example, Listing 3-25 ' s
convert() methodspecifiesathrowsclauseindicatingthat convert() canthrow
InvalidMediaFormatException , which is currently thrown, and IOExcep-
tion ,whichwillbethrownwhen convert() isrefactored.Thisrefactoringwillres-
ultin convert() throwing IOException whenitcannotreadfromthesourcefile
orwritetothedestinationfile,andthrowing FileNotFoundException (asubclass
of IOException )whenitcannotopenthesourcefileorcreatethedestinationfile.All
these exceptions must be handled, as demonstrated in Listing 3-26 .
Search WWH ::




Custom Search