Java Reference
In-Depth Information
}
catch
(InvalidMediaFormatException
|
UnsupportedMedi-
aFormatException imfeumfe)
{
// common code to respond to these similar exceptions
}
This example assumes that
convert()
is also capable of throwing
me-
dia.UnsupportedMediaFormatException
whenitdetectsamediaformatthat
it cannot handle (such as a video format). When
convert()
throws either
Inval-
idMediaFormatException
or
UnsupportedMediaFormatException
, the
catch block will handle either exception.
Whenmultipleexceptiontypesarelistedinacatchblock'ssingleparameterlist,the
parameterisimplicitlyregardedas
final
.Asaresult,youcannotchangetheparamet-
er's value. For example, you cannot change the reference stored in the example's
im-
feumfe
parameter.
Multicatchisnotalwaysnecessary.Forexample,youdonotneedtospecify
catch
(FileNotFoundException | IOException fnfeioe) { /* suitable
common code */ }
tohandle
FileNotFoundException
and
IOException
because
catch (IOException ioe)
accomplishes the same task, by catching
FileNotFoundException
as well as
IOException
. For this reason, the com-
pilerreportsanerrorwhenitdetectsacatchblockwhoseparameterlistexceptiontypes
include a supertype and a subtype.
Note
The bytecode resulting from compiling a catch block that handles multiple
exception types will be smaller than compiling several catch blocks that each handle
only one of the listed exception types. A catch block that handles multiple exception
types contributes no duplicate bytecode during compilation. In other words, the byte-
code doesn't contain replicated exception handlers.
Rethrowing Exceptions
While discussing the
Throwable
class, I discussed wrapping lower-level exceptions
inhigher-levelexceptions.Thisactivitywilltypicallytakeplaceinacatchblock,andis
illustrated in the following example:
catch (IOException ioe)
{