Java Reference
In-Depth Information
What Are Exceptions?
An exception is a divergence from an application's normal behavior. For example, the
application attempts to open a nonexistent file for reading. The normal behavior is to
successfully open the file and begin reading its contents. However, the file cannot be
read if the file does not exist.
This example illustrates an exception that cannot be prevented. However, a work-
aroundispossible.Forexample,theapplicationcandetectthatthefiledoesnotexistand
takeanalternatecourseofaction,whichmightincludetellingtheuserabouttheprob-
lem. Unpreventable exceptions where workarounds are possible must not be ignored.
Exceptions can occur because of poorly written code. For example, an application
mightcontaincodethataccesseseachelementinanarray.Becauseofcarelessoversight,
thearray-accesscodemightattempttoaccessanonexistentarrayelement,whichleads
to an exception. This kind of exception is preventable by writing correct code.
Finally,anexceptionmightoccurthatcannotbeprevented,andforwhichthereisno
workaround.Forexample,theJVMmightrunoutofmemory,orperhapsitcannotfind
aclassfile.Thiskindofexception,knownasan error ,issoseriousthatitisimpossible
(or at least inadvisable) to work around; the application must terminate, presenting a
message to the user that explains why it is terminating.
Representing Exceptions in Source Code
Anexceptioncanberepresentedviaerrorcodesorobjects.Afterdiscussingeachkindof
representationandexplainingwhyobjectsaresuperior,IintroduceyoutoJava'sexcep-
tionanderrorclasshierarchy,emphasizingthedifferencebetweencheckedandruntime
exceptions.Iclosemydiscussiononrepresentingexceptionsinsourcecodebydiscuss-
ing custom exception classes.
Error Codes Versus Objects
One way to represent exceptions in source code is to use error codes. For example, a
methodmightreturntrueonsuccessandfalsewhenanexceptionoccurs.Alternatively,
amethodmightreturn0onsuccessandanonzerointegervaluethatidentifiesaspecific
kind of exception.
Developerstraditionallydesignedmethodstoreturnerrorcodes;Idemonstratedthis
traditionineachofthethreemethodsin Listing3-17 ' s Logger interface.Eachmethod
returnstrueonsuccess,orreturnsfalsetorepresentanexception(unabletoconnectto
the logger, for example).
Search WWH ::




Custom Search