Java Reference
In-Depth Information
blocksillustratetheoften-seenproblemofleavingcatchblocksemptybecausetheyare
inconvenient to code. Unless you have a good reason, do not create an empty catch
block. It swallows exceptions and you do not know that the exceptions were thrown.
(For brevity, I don't always code catch blocks in this topic's examples.)
Caution
Thecompilerreportsanerrorwhenyouspecifytwoormorecatchblocks
withthesameparametertypeafteratrybody.Example:
try {} catch (IOEx-
ception ioe1) {} catch (IOException ioe2) {}
. You must merge
these catch blocks into one block.
Although you can write catch blocks in any order, the compiler restricts this order
whenonecatchblock'sparameterisasupertypeofanothercatchblock'sparameter.The
subtypeparametercatchblockmustprecedethesupertypeparametercatchblock;oth-
erwise, the subtype parameter catch block will ever be executed.
For example, the
FileNotFoundException
catch block must precede the
IOException
catch block. If the compiler allowed the
IOException
catch block
tobespecifiedfirst,the
FileNotFoundException
catchblockwouldeverexecute
becausea
FileNotFoundException
instanceisalsoaninstanceofits
IOExcep-
tion
superclass.
Multicatch
Supposeyouhavetwoormorecatchblockswhosecodeisidenticalorearlyidentical.
To eliminate this redundancy, you might be tempted to refactor this code into a single
catchblockwithacommonsuperclassexceptiontype(suchas
catch (Exception
e) {}
).However,catchingoverlybroadexceptionsisnotagoodideabecausedoingso
masksthepurposeforthehandler(whatexceptionsarehandledbycatch
(Exception
e) {}
, for example). Also, the single catch block might inadvertently handle thrown
exceptionsthatshouldbehandledelsewhere.(Perhapstheseexceptionsarethrownasa
result of refactored code.)
Java provides the
multicatch
language feature to avoid redundancy and also the prob-
lems inherent with catching overly broad exceptions. Multicatch lets you specify mul-
tipleexceptiontypesinacatchblockwhereeachsuccessivetypeisseparatedfromits
predecessorbyplacingaverticalbar(|)betweenthesetypes.Considerthefollowingex-
ample:
try
{
Media.convert(args[0], args[1]);