Java Reference
In-Depth Information
(
CloneNotSupportedException
should not be checked because there is no
runtime workaround for this kind of exception.)
A
runtime exception
isanexceptionthatrepresentsacodingmistake.Thiskindofex-
ceptionisalsoknownasan
unchecked exception
becauseitdoesnotneedtobehandled
orexplicitlyidentified—themistakemustbefixed.Becausetheseexceptionscanoccur
in many places, it would be burdensome to be forced to handle them.
RuntimeException
and its subclasses describe unchecked exceptions. For ex-
ample,
java.lang.ArithmeticException
describes arithmetic problems such
as integer division by zero. Another example is
java.lang.ArrayIndexOutOfBoundsException
. (In hindsight,
RuntimeException
should have been named
UncheckedException
because
all exceptions occur at runtime.)
Note
Manydevelopersarenothappywithcheckedexceptionsbecauseofthework
involvedinhavingtohandlethem.Thisproblemismadeworsebylibrariesproviding
methodsthatthrowcheckedexceptionswhentheyshouldthrowuncheckedexceptions.
As a result, many modern languages support only unchecked exceptions.
Custom Exception Classes
Youcandeclareyourownexceptionclasses.Beforedoingso,askyourselfifanexisting
exceptionclassinJava'sstandardclasslibrarymeetsyourneeds.Ifyoufindasuitable
class,youshouldreuseit.(Whyreinventthewheel?)Otherdeveloperswillalreadybe
familiarwiththeexistingclass,andthisknowledgewillmakeyourcodeeasiertolearn.
Ifnoexistingclassmeetsyourneeds,thinkaboutwhethertosubclass
Exception
or
RuntimeException
.Inotherwords,willyourexceptionclassbecheckedorun-
checked?Asaruleofthumb,yourclassshouldsubclass
RuntimeException
ifyou
think that it will describe a coding mistake.
Tip
Whenyounameyourclass,followtheconventionofprovidingan
Exception
suffix. This suffix clarifies that your class describes an exception.
Suppose you are creating a
Media
class whose static methods perform various
media-oriented utility tasks. Forexample, one method converts soundfiles in on-MP3
media formats to MP3 format. This method will be passed source file and destination
filearguments,andwillconvertthesourcefiletotheformatimpliedbythedestination
file's extension.
Before performing the conversion, the method needs to verify that the source file's
formatagreeswiththeformatimpliedbyitsfileextension.Ifthereisnoagreement,an