Exception
Exception
Exceptions
CSC 113
King Saud University
College of Computer and Information Sciences
Department of Computer Science
Dr. S. HAMMAMI
Objectives
•• After
Afteryou
youhave
haveread
readand
andstudied
studiedthis
thischapter,
chapter,you
youshould
should
beable
be ableto
to
–– Improve
Improvethe
thereliability
reliabilityof
ofcode
codeby
byincorporating
incorporatingexception-handling
exception-handling
andassertion
and assertionmechanisms.
mechanisms.
–– Write
Writemethods
methodsthat
thatpropagate
propagateexceptions.
exceptions.
–– Implement
Implementthe
thetry-catch
try-catchblocks
blocksfor
forcatching
catchingand
andhandling
handling
exceptions.
exceptions.
–– Write
Writeprogrammer-defined
programmer-definedexception
exceptionclasses.
classes.
–– Distinguish
Distinguishthe
thechecked
checkedand
andunchecked,
unchecked,or
orruntime,
runtime,exceptions.
exceptions.
Introduction to Exception Handling
•• No
Nomatter
matterhow
howwell
welldesigned
designedaaprogram
programis, is,there
thereisisalways
alwaysthe
thechance
chancethat
that
somekind
some kindof
oferror
errorwill
willarise
ariseduring
duringits
itsexecution.
execution.
•• AAwell-designed
well-designedprogram
programshould
shouldinclude
includecode
codetotohandle
handleerrors
errorsand
andother
other
exceptionalconditions
exceptional conditionswhen
whenthey
theyarise.
arise.
•• Sometimes
Sometimesthe
thebest
bestoutcome
outcomecan
canbe
bewhen
whennothing
nothingunusual
unusualhappens
happens
•• However,
However,the
thecase
casewhere
whereexceptional
exceptionalthings
thingshappen
happenmust
mustalso
alsobe
be
preparedfor
prepared for
–– Java
Javaexception
exceptionhandling
handlingfacilities
facilitiesare
areused
usedwhen
whenthetheinvocation
invocationof
of
aamethod
methodmay
maycause
causesomething
somethingexceptional
exceptionalto
tooccur
occur
Introduction to Exception Handling
•• Java
Javalibrary
librarysoftware
software(or
(orprogrammer-defined
programmer-definedcode)
code)
providesaamechanism
provides mechanismthat
thatsignals
signalswhen
whensomething
something
unusualhappens
unusual happens
–– This
Thisisiscalled
calledthrowing
throwingan
anexception
exception
•• In
Inanother
anotherplace
placein
inthe
theprogram,
program,the
theprogrammer
programmer
mustprovide
must providecode
codethat
thatdeals
dealswith
withthe
theexceptional
exceptional
case
case
–– This
Thisisiscalled
calledhandling
handlingthe
theexception
exception
Definition
•• An
An exception
exception represents
represents an
an error
error condition
condition that
that
can occur
can occur during
during the
the normal
normal course
course of
of program
program
execution.
execution.
•• When
When anan exception
exception occurs,
occurs, or or is
is thrown,
thrown, the
the
normal sequence
normal sequence of
of flow
flow is
is terminated.
terminated.
•• The
The exception-handling
exception-handling routine
routine isis then
then executed;
executed;
we say
we say the
the thrown
thrown exception
exception is
is caught.
caught.
Not Catching Exceptions
•• TheavgFirstN()
The avgFirstN()method
methodexpects
expectsthat
thatNN>>0.
0.
•• IfIfNN==0,
0,aadivide-by-zero
divide-by-zeroerror
erroroccurs
occursinin avg/N.
avg/N.
/**
* Precondition: N > 0
* Postcondition: avgFirstN() equals the average of (1+2+…+N)
*/
public double avgFirstN(int N) {
duuble sum = 0;
for (int k = 1; k <= N; k++)
sum += k;
return sum/N; // What if N is 0 ??
} // avgFirstN()
classAgeInputVer1
class AgeInputVer1{{ publicclass
public classAgeInputMain2
AgeInputMain2{{
privateint
private intage;
age; publicstatic
public staticvoid
voidmain(
main(String[]
String[]args
args) ){{
publicvoid
public voidsetAge(String
setAge(Strings)s){{ AgeInputVer1PP==new
AgeInputVer1 newAgeInputVer1(
AgeInputVer1(););
age==Integer.parseInt(s);
age Integer.parseInt(s); P.setAge("9");
P.setAge("9");
}} System.out.println(P.getAge());
System.out.println(P.getAge());
publicint
public intgetAge()
getAge(){{ }}
returnage;
return age; }}
}}
9
}}
Java’s Exception Hierarchy
Class
Class Description
Description
ArithmeticException
ArithmeticException Divisionby
Division byzero
zeroor
orsome
someother
otherkind
kindofofarithmetic
arithmeticproblem
problem
ArrayIndexOutOfBounds-
ArrayIndexOutOfBounds- Anarray
An arrayindex
indexisisless
lessthan
thanzero
zeroor
orException
Exceptiongreater
greaterthan
thanor
or
equaltotothe
equal thearray's
array'slength
length
FileNotFoundException
FileNotFoundException Referencetotoaaunfound
Reference unfoundfile
fileIllegalArgumentException
IllegalArgumentException
Methodcall
Method callwith
withimproper
improperargument
argument
IndexOutOfBoundsException
IndexOutOfBoundsException Anarray
An arrayor
orstring
stringindex
indexout
outofofbounds
bounds
NullPointerException
NullPointerException Referencetotoan
Reference anobject
objectwhich
whichhas
hasnot
notbeen
beeninstantiated
instantiated
NumberFormatException
NumberFormatException Useofofan
Use anillegal
illegalnumber
numberformat,
format,such
suchasaswhen
whencalling
callingaamethod
method
StringIndexOutOfBoundsException
StringIndexOutOfBoundsException AAString
Stringindex
indexless
lessthan
thanzero
zeroor
orgreater
greaterthan
thanor
orequal
equal
totothe
theString's
String'slength
length
Catching an Exception
class AgeInputVer2
class AgeInputVer2 {{
private int
private int age
age
public void
public void setAge(String
setAge(String s)
s)
{{
try {{
try
We are catching the number format
exception, and the parameter e
try age == Integer.parseInt(s);
age Integer.parseInt(s); represents an instance of the
NumberFormatException class
}} catch
catch (NumberFormatException
(NumberFormatException e){
e){
catch System.out.Println(“age
System.out.Println (“age is
is invalid,
invalid, Please
Please enter
enter digits
digits only" );
only");
}}
}}
public int
public int getAge()
getAge() {{ return age;
return age; }}
}}
Catching an Exception
To accomplish this repetition, we will put the whole try-catch statement in side a loop:
importjava.util.Scanner;
import java.util.Scanner;
classAgeInputVer3
class AgeInputVer3{{
privateint
private intage;
age;
publicvoid
public voidsetAge(String
setAge(Strings)s){{
Stringmm=s;
String =s;
Scannerinput
Scanner input==new
newScanner(System.in);
Scanner(System.in);
booleanok
boolean ok==true;
true;
while(ok)
while (ok){{
try{{ Thisstatement
This statement
try
age==Integer.parseInt(m);
age Integer.parseInt(m); isisexecuted
executedonly
only
ok==false;
false; ififno
noexception
exception
ok
isisthrown
thrownbyby
}}catch
catch(NumberFormatException
(NumberFormatExceptione){
e){
parseInt.
System.out.println(“ageisisinvalid,
invalid,Please
Pleaseenter
enterdigits
digitsonly");
only");
parseInt.
System.out.println(“age
mm==input.next();
input.next();
}}
}}
publicint
public intgetAge()
getAge(){{ return
returnage;
age; }}
}}
try-catch Control Flow
The Exception Class: Getting Information
• There are two methods we can call to get information about the thrown exception:
– getMessage
– printStackTrace
Simple: only
constructor
methods.
The Exception Class: Getting Information
We are catching the number format
exception, and the parameter e represents an
instance of the NumberFormatException
class
try {
. . .
} catch (NumberFormatException e){
System.out.println(e.getMessage());
System.out.println(e.printStackTrace());
}
thrownew
throw new
ExceptionClassName(PossiblySomeArguments);
ExceptionClassName(PossiblySomeArguments);
•• When
Whenan
anexception
exceptionisisthrown,
thrown,the
theexecution
executionofofthe
thesurrounding
surroundingtry
tryblock
blockisisstopped
stopped
–– Normally,
Normally,the
theflow
flowofofcontrol
controlisistransferred
transferredtotoanother
anotherportion
portionofofcode
codeknown
knownasasthe
the
catchblock
catch block
•• The
Thevalue
valuethrown
thrownisisthe
theargument
argumenttotothe
thethrow
throwoperator,
operator,and
andisisalways
alwaysan
anobject
objectofofsome
some
exceptionclass
exception class
–– The
Theexecution
executionofofaathrow
throwstatement
statementisiscalled
calledthrowing
throwingan
anexception
exception
try-throw-catch Mechanism
•• AAthrow
throwstatement
statementisissimilar
similartotoaamethod
methodcall:
call:
–– throw
thrownew
newExceptionClassName(SomeString);
ExceptionClassName(SomeString);
–– InInthe
theabove
aboveexample,
example,the
theobject
objectofofclass
classExceptionClassName
ExceptionClassNameisiscreated
createdusing
usingaa
stringasasits
string itsargument
argument
–– This
Thisobject,
object,which
whichisisan
anargument
argumenttotothe
thethrow
throwoperator,
operator,isisthe
theexception
exceptionobject
object
thrown
thrown
•• Instead
Insteadofofcalling
callingaamethod,
method,aathrow
throwstatement
statementcalls
callsaacatch
catchblock
block
try-throw-catch Mechanism
•• When
Whenan
anexception
exceptionisisthrown,
thrown,the
thecatch
catchblock
blockbegins
beginsexecution
execution
–– The
Thecatch
catchblock
blockhas
hasone
oneparameter
parameter
–– The
Theexception
exceptionobject
objectthrown
thrownisisplugged
pluggedininfor
forthe
thecatch
catchblock
blockparameter
parameter
•• The
Theexecution
executionofofthe
thecatch
catchblock
blockisiscalled
calledcatching
catchingthe
theexception,
exception,ororhandling
handlingthe
the
exception
exception
–– Whenever
Wheneverananexception
exceptionisisthrown,
thrown,ititshould
shouldultimately
ultimatelybe
behandled
handled(or
(orcaught)
caught)by
by
somecatch
some catchblock
block
try-throw-catch Mechanism
•• When
Whenaatry blockisisexecuted,
tryblock executed,twotwothings
thingscan
canhappen:
happen:
1. No
1. Noexception
exceptionisisthrown
thrownininthe
thetry
tryblock
block
–– The
Thecode
codeininthe
thetry blockisisexecuted
tryblock executedtotothe
theend
endof
ofthe
theblock
block
–– The
Thecatch blockisisskipped
catchblock skipped
–– The
Theexecution
executioncontinues
continueswith
withthe
thecode
codeplaced
placedafter
afterthe
the
block
catchblock
catch
•• 2.
2. An
Anexception
exceptionisisthrown
thrownininthethetry
tryblock
blockand
andcaught
caughtininthe
thecatch
catch
block
block
Therest
The restof ofthe
thecode
codeininthethetry
tryblock
blockisisskipped
skipped
Controlisistransferred
Control transferredto toaafollowing
followingcatch
catchblock
block(in
(insimple
simplecases)
cases)
Thethrown
The thrownobject
objectisisplugged
pluggedininfor
forthe
thecatch
catchblock
blockparameter
parameter
Thecode
The codeininthethecatch
catchblock
blockisisexecuted
executed
Thecode
The codethatthatfollows
followsthat
thatcatch
catchblock
blockisisexecuted
executed(if(ifany)
any)
public class CalcAverage {
public double avgFirstN(int N ){
double sum = 0;
try {
if (N <=0)
throw new Exception("ERROR: Can't average 0 elements");
for (int k = 1; k <= N; k++)
sum += k;
return sum/N;
}
}
•• AAtry
tryblock
blockcan
canpotentially
potentiallythrow
throwany
anynumber
numberof ofexception
exceptionvalues,
values,
andthey
and theycan
canbe
beof
ofdiffering
differingtypes
types
–– In
Inany
anyone
oneexecution
executionofofaatry
tryblock,
block,atatmost
mostone
oneexception
exceptioncan
can
bethrown
be thrown(since
(sinceaathrow
throwstatement
statementends
endsthe
theexecution
executionof
ofthe
thetry
try
block)
block)
–– However,
However,different
differenttypes
typesofofexception
exceptionvalues
valuescan
canbe
bethrown
thrownonon
differentexecutions
different executionsofofthe
thetry
tryblock
block
•• Each
Eachcatch
catchblock
blockcan
canonly
onlycatch
catchvalues
valuesof
ofthe
theexception
exceptionclass
classtype
type
givenininthe
given thecatch
catchblock
blockheading
heading
•• Different
Differenttypes
typesofofexceptions
exceptionscan
canbe
becaught
caughtbybyplacing
placingmore
morethan
than
onecatch
one catchblock
blockafter
afteraatry
tryblock
block
–– Any
Anynumber
numberof ofcatch
catchblocks
blockscan
canbe
beincluded,
included,but
butthey
theymust
mustbebe
placedininthe
placed thecorrect
correctorder
order
Multiple catch Blocks
Multiple catch Control Flow
Multiple catch Control Flow: Example
importjava.util.*;
java.util.*;//InputMismatchException;
//InputMismatchException; catch (InputMismatchException var1 )
import catch (InputMismatchException var1 )
//import java.util.ArithmeticException; { System.out.println("Exception :"+ var1);
//import java.util.ArithmeticException; { System.out.println("Exception :"+ var1);
publicclass
classDividbyZero2
DividbyZero2 System.out.println("please try again: ");
public System.out.println("please try again: ");
{{ public
publicstatic
staticvoid
voidmain
main(String
(Stringargs[])
args[])//throws
//throwsArithmeticException
ArithmeticException }
}
{{Scanner
Scannerinput
input==new
newScanner(System.in);
Scanner(System.in); catch(ArithmeticException var2)
catch(ArithmeticException var2)
booleandone=false;
done=false; {
boolean {
do{{ System.out.println("\nException :"+ var2);
do System.out.println("\nException :"+ var2);
try System.out.println("Zero is an valid denomiattor");
try System.out.println("Zero is an valid denomiattor");
{System.out.print("Pleaseenter
enterananinteger
integernumber
number: :");
"); }
{System.out.print("Please }
inta a=input.nextInt();
=input.nextInt(); }while(!done);
int }while(!done);
System.out.print("Pleaseenter
enterananinteger
integernumber
number: :");
"); }
System.out.print("Please }
intbb=input.nextInt();
=input.nextInt(); }
int }
intc=a/b;
c=a/b;
int
Please enter an integer number : car
System.out.println("a="+
="+a a+"+"b=
b="+b+
"+b+" " amd
amdquotient
quotient="+c);
="+c); Please enter an integer number : car
System.out.println("a Exception :java.util.InputMismatchException
Exception :java.util.InputMismatchException
done=true;
done=true; You must enter an integer value, please try again:
You must enter an integer value, please try again:
}} Please enter an integer number : 14
Please enter an integer number : 14
Please enter an integer number : 0
Please enter an integer number : 0
•• When
When catching
catching multiple
multiple exceptions,
exceptions, the
the
order of
order of the
the catch blocks is
catch blocks is important
important
–– When
Whenananexception
exceptionisisthrown
thrownin
inaa try block,the
tryblock, the
blocksare
catchblocks
catch areexamined
examinedin inorder
order
–– The
Thefirst
firstone
onethat
thatmatches
matchesthethetype
typeof ofthe
the
exceptionthrown
exception thrownisisthe
theone
onethat
thatisisexecuted
executed
The finally Block
try-catch-finally Control Flow
try-catch-finally Control Flow
•• IfIfthe
thetry-catch-finally
try-catch-finallyblocks blocksareareinside
insideaamethod
method
definition,there
definition, thereare
arethree
threepossibilities
possibilitieswhen
whenthethecode
codeisisrun:
run:
1.
1. Thetry
The blockruns
tryblock runsto tothe
theend,
end,no
noexception
exceptionisisthrown,
thrown,and
andthe
the
blockisisexecuted
finallyblock
finally executed
2.
2. Anexception
An exceptionisisthrown
thrownininthe
thetry block,caught
tryblock, caughtininone
oneof
ofthe
the
blocks,and
catchblocks,
catch andthe
thefinally blockisisexecuted
finallyblock executed
3.
3. AnAnexception
exceptionisisthrown
thrownininthe
thetry block,there
tryblock, thereisisno
nomatching
matching
blockininthe
catchblock
catch themethod,
method,thethefinally blockisisexecuted,
finallyblock executed,
andthen
and thenthe
themethod
methodinvocation
invocationends
endsand
andthetheexception
exceptionobject
object
isisthrown
thrownto
tothe
theenclosing
enclosingmethod
method
Propagating Exceptions
Throwing an Exception in a Method
•• Sometimes
Sometimesititmakes
makessensesenseto
tothrow
throwan
anexception
exceptionininaamethod,
method,
butnot
but notcatch
catchititininthe
thesame
samemethod
method
–– Some
Someprograms
programsthat
thatuse
useaamethod
methodshould
shouldjust
justend
endififan
anexception
exception
isisthrown,
thrown,and
andother
otherprograms
programsshould
shoulddo
dosomething
somethingelseelse
–– In
Insuch
suchcases,
cases,the
theprogram
programusing
usingthe
themethod
methodshould
should enclose
enclosethe
the
methodinvocation
method invocationininaatry
tryblock,
block,and
andcatch
catchthe
theexception
exceptionininaa
catchblock
catch blockthat
thatfollows
follows
•• In
Inthis
thiscase,
case,the
themethod
methoditself
itselfwould
wouldnot
notinclude
includetry
tryand
andcatch
catchblocks
blocks
–– However,
However,ititwould
wouldhave
havetotoinclude
includeaathrows
throwsclause
clause
Declaring Exceptions in a throws Clause
•• IfIfaamethod
methodcan
canthrow
throwan
anexception
exceptionbut
butdoes
doesnot
notcatch
catchit,it,itit
mustprovide
must provideaawarning
warning
–– This
Thiswarning
warningisiscalled
calledaathrows
throwsclause
clause
–– The
Theprocess
processofofincluding
includingan
anexception
exceptionclass
classininaathrows
throwsclause
clauseisis
calleddeclaring
called declaringthe
theexception
exception
throwsAnException
throws AnException //throws
//throwsclause
clause
–– The
Thefollowing
followingstates
statesthat
thatan
aninvocation
invocationof
ofaMethod
aMethodcould
couldthrow
throw
AnException
AnException
publicvoid
public voidaMethod()
aMethod()throws
throwsAnException
AnException
Declaring Exceptions in a throws Clause
•• IfIfaamethod
methodcan
canthrow
throwmore
morethan
thanone
onetype
typeof
ofexception,
exception,then
then
separatethe
separate theexception
exceptiontypes
typesby
bycommas
commas
public void
public void aMethod()
aMethod() throws
throwsAnException,AnotherException
AnException,AnotherException
•• IfIfaamethod
methodthrows
throwsan
anexception
exceptionand
anddoes
doesnot
notcatch
catchit,
it,then
then
themethod
the methodinvocation
invocationends
endsimmediately
immediately
Exception propagation and throws clause
Method
Method getDepend()
getDepend() //// postcondition:Returns
postcondition: Returnsint
intvalue
valueofofaanumeric
numericdata
datastring.
string.
// Throws an exception if string is not numeric.
// Throws an exception if string is not numeric.
may throw
may throw aa number
number
publicstatic
public staticint
intgetDepend()
getDepend()throws
throwsNumberFormatException
NumberFormatException{{
format exception
format exception when when
StringnumStr
String numStr==jnputnext();
jnputnext();
converting aa string
converting string toto an
an
returnInteger.parseInt(numStr);
return Integer.parseInt(numStr);
integer, but
integer, but itit does
does notnot
catchthis
thisexception.
exception. }}
catch
////postcondition:
postcondition:Calls
CallsgetDepend()
getDepend()and
andhandles
handlesits
itsexceptions.
exceptions.
The call
The call toto getDepend()
getDepend() publicstatic
staticvoid
voidmain(String[]
main(String[]args)
args){{
public
occursininthe
occurs thetry
tryblock
blockof
of intchildren
children==1;1; ////problem
probleminput,
input,default
defaultisis11
int
method main(),
method main(), so so try{{
try children==getDepend();
getDepend();
main() handles
main() handles the the } children
exception inin its its catch
catch }
exception catch(NumberFormatException
(NumberFormatExceptionex) ex){{
block. catch
block.
////Handle
Handlenumber
numberformat
formatexception.
exception.
System.out.println("Invalidinteger“
System.out.println("Invalid integer“++ex);
ex);
IfIf main()
main() did
did not
not have
have aa
catch block
block for
for number
number }}}
catch }
format exceptions,
format exceptions, the
the
exception would
exception would be be
handledby
handled bythe
theJVM.
JVM.
Exception Thrower
•• When
When aa method
method maymay throw
throw anan exception,
exception, either
either
directly or
directly or indirectly,
indirectly, we
we call
call the
the method
method an
an
exception thrower.
exception thrower.
•• Every
Every exception
exception thrower
thrower must
must be
be one
one of
of two
two types:
types:
–– catcher.
catcher.
–– propagator.
propagator.
Types of Exception Throwers
•• An
An exception
exception catcher
catcher is
is an
an exception
exception thrower
thrower that
that
includes aa matching
includes matching catch
catch block
block for
for the
the thrown
thrown
exception.
exception.
•• An
An exception
exception propagator
propagator does
does not
not contain
contain aa
matching catch
matching catch block.
block.
•• AA method
method may
may bebe aa catcher
catcher of
of one
one exception
exception and
and
aa propagator
propagator of
of another.
another.
Sample Call Sequence
MethodAAcalls
Method callsmethod
methodB,
B,
Every time a method is executed, the
MethodBBcalls
Method callsmethod
methodC,
C,
method’s name is placed on top of the stack.
MethodCCcalls
Method callsmethod
methodD.
D.
Sample Call Sequence
¾Whenan
¾When anexception
exceptionisisthrown,
thrown,the
thesystem
systemsearches
searchesdown
downthe
thestack
stackfrom
from
thetop,
the top,looking
lookingfor
forthe
thefirst
firstmatching
matchingexception
exceptioncatcher.
catcher.
¾MethodDDthrows
¾Method throwsan
anexception,
exception,but
butno
nomatching
matchingcatch
catchblock
blockexits
exitsininthe
the
method,so
method, somethod
methodDDisisan
anexception
exceptionpropagator.
propagator.
¾Thesystem
¾The systemthen
thenchecks
checksmethod
methodC.
C.CCisisalso
alsoan
anexception
exceptionpropagator.
propagator.
¾Finally,the
¾Finally, thesystem
systemlocates
locatesthe
thematching
matchingcatch
catchblock
blockininmethod
methodB,
B,and
and
therefore,method
therefore, methodBBisisthe
thecatcher
catcherfor
forthe
theexception
exceptionthrown
thrownbybymethod
methodD.
D.
¾MethodAAalso
¾Method alsoincludes
includesthe
thematching
matchingcatch
catchblock,
block,but
butititwill
willnot
notbe
be
executedbecause
executed becausethe
thethrown
thrownexception
exceptionisisalready
alreadycaught
caughtby bymethod
methodBBand
and
methodBBdoes
method doesnot
notpropagate
propagatethis
thisexception.
exception.
voidC()
void C()throws
throwsException
Exception{{ voidD()
void D()throws
throwsException
Exception{{
….
…. ….
….
}} }}
Example
Considerthe
theFraction
Fractionclass.
class.The
The Throwingan
Throwing anexception
exceptionisisaamuch
muchbetter
better
Consider approach.Here’s
Here’sthe
themodified
modifiedmethod
methodthat
that
setDenominatormethod
setDenominator methodofofthe
the approach.
Fractionclass
class throwsan
throws anIlleglArgumentException
IlleglArgumentExceptionwhen whenthethe
Fraction valueofof00isispassed
passedasasan
anargument:
argument:
wasdefined
was definedasasfollows:
follows: value
publicvoid
public voidsetDenominator
setDenominator(int
(intd)d)
publicvoid
public voidsetDenominator
setDenominator(int
(intd)d)
throwsIlleglArgumentException
throws IlleglArgumentException
{{
{{
ifif(d(d====0)0)
ifif(d(d====0)0)
{{
System.out.println(“FatalError”);
Error”); {{
System.out.println(“Fatal thrownew
newIlleglArgumentException
IlleglArgumentException(“Fatal
(“FatalError”);
Error”);
System.exit(1); throw
System.exit(1);
}}
denominator==d;d; }}
denominator denominator==d;d;
denominator
}}
}}
Programmer-Defined Exception Classes
• A throw statement can throw an exception object of any exception class
• Instead of using a predefined class, exception classes can be programmer-
defined
– These can be tailored to carry the precise kinds of information needed in
the catch block
– A different type of exception can be defined to identify each different
exceptional situation
• The exception class should allow for the fact that the method
getMessage is inherited
Programmer-Defined Exceptions: AgeInputException