chapter8 exception handling
TRANSCRIPT
-
7/23/2019 Chapter8 Exception Handling
1/34
1
-
7/23/2019 Chapter8 Exception Handling
2/34
xception Handling in
Java
Types of rrors
1.Compile time
All syntax errors identified by java
compiler.
No class file is created wen tis occ!rs.
"o it is necessary to fix all compile time
errors for s!ccessf!l compilation.
gs#
$issing of semicolon%
!se of & instead of &&
2
-
7/23/2019 Chapter8 Exception Handling
3/34
xception Handling in
Java
'.(!n time
"ome pgms may not r!n s!ccessf!lly d!e
to wrong logic or errors li)e stac)
overflow.
"ome of te Common r!n time errors are#
*ivision by +
Array index o!t of bo!nds
Negative array si,e etc..
3
-
7/23/2019 Chapter8 Exception Handling
4/34
xception Handling in
Java
xception is a condition ca!sed by a r!n time
error in te program. -en te java interpreter
identifies an error s!c as division by + it
creates an xception object and trows it
*efinition#
An
e eption
is an event% wic occ!rs d!ring
te exec!tion of a program% tat disr!pts te
normal flow of te program/s instr!ctions.
0s defined as a condition tat interr!pts te
normal flow of operation witin a program.
4
-
7/23/2019 Chapter8 Exception Handling
5/34
Exception Handling in Java
Java allows xception andling mecanism to
andle vario!s exceptional conditions. -en an
exceptional condition occ!rs% an e eptionis
said to be trown.
or contin!ing te program exec!tion% te !ser
so!ld try to catc te exception object trown
by te error condition and ten display an
appropriate message for ta)ing corrective
actions. Tis tas) is )nown as xception
andling
5
-
7/23/2019 Chapter8 Exception Handling
6/34
xception Handling in
Java
Tis mecanism consists of #
1. ind te problem2Hit te xception3
'. 0nform tat an error as occ!rred2Trow
te xception3
4. (eceive te error 0nformation2Catc te
xception3
5. Ta)e corrective actions2Handle te
xception3
6
-
7/23/2019 Chapter8 Exception Handling
7/34
xception Handling in
Java
0n Java xception andling is managed by 6
)ey words#
try
catc
trow
trows
finally
7
-
7/23/2019 Chapter8 Exception Handling
8/34
xception Handling in Java
8
Trowable
Exception error
0nterr!ptedException
2cec)ed exception3
(!ntimeException
2!ncec)ed exception3
xception
Hierarcy
7ac)age java.lang
-
7/23/2019 Chapter8 Exception Handling
9/34
xception Handling in Java
8ncec)ed exception#Tese exception need not be incl!ded in an
metod9s trowslistTe compiler does not cec) to see if a metod
andles or trows tese exception
tese are s!bclasses of (!ntime xceptionTe compiler doesn/t force client programmerseiter to catc te exception or declare it in atrows cla!se.
Class Error and its s!bclasses also are !ncec)ed.Cec)ed exception#
$!st be incl!ded in an metod9s trowslist if tatmetod can generate one of tose exceptions and doesnot andle it itself
Tese exception defined by java.lang
9
-
7/23/2019 Chapter8 Exception Handling
10/34
xception Handling in Java
10
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreException Assignment to an array element of anincompatible type
lassastException Invalid cast
Enumonstant!ot"resentException An attempt is made to use an unde#nedenumeration value
IllegalArgumentException Illegal argument used to invo$e a method
Illegal%onitorStateException Illegal monitor operation, such as &aiting onan unloc$ed thread
IllegalStateException Environment or application is in incorrectstate
Illegal'hreadStateException (e)uested operation not compatible &ithcurrent thread state
IndexOutOfBoundsException Some type of index is out-of-bounds
!egativeArraySizeException Array created &ith a negative size
Javas unchecked RuntimeException subclasses defined injava.lang
-
7/23/2019 Chapter8 Exception Handling
11/34
xception Handling in Java
11
Exception Meaning
!ull"ointerException Invalid use of a null reference
!umber*ormatException Invalid conversion of a string to a numericformat
SecurityException Attempt to violate security
StringIndexOutOfBoundsException Attempt to index outside the bounds of a
string
'ype!ot"resentException 'ype not fount
+nsupportedOperationException An unsupported operation &as encountered
-
7/23/2019 Chapter8 Exception Handling
12/34
xception Handling in Java
12
Javas checked Exceptindefined injava.lang
Exception Meaning
lass!ot*oundException lass not found
lone!otSupportedException Attempt to clone an obect that does notimplement the Cloneable interface
IllegalAccessException Access to a class is denied
InstantiationException Attempt to create an obect of an abstractclass or interface
InterruptedException One thread has been interrupted by anotherthread
!oSuch*ieldException A re)uested #eld does not exist!oSuch%ethodException A re)uested method does not exist
-
7/23/2019 Chapter8 Exception Handling
13/34
xception Handling in Java
class x:
p!blic static void main2"tring args;
-
7/23/2019 Chapter8 Exception Handling
14/34
xception Handling in
Java
try @ catc
try Block
Statement that
causes Exception
Catch Block
Statement that
causes Exception
14
-
7/23/2019 Chapter8 Exception Handling
15/34
xception Handling in
Java
try:"tatement#
?
catc2Exceptiontype e3:
statement=
?
15
-
7/23/2019 Chapter8 Exception Handling
16/34
xception Handling in
Javaclass Ex:
p!blic static void main2"tring args;d=
"ystem.o!t.println2Bfrom tryB3=
?catc2AritmeticException e3
:
"ystem.o!t.println2Bdivsn by eroB3=
?
"ystem.o!t.println2Bafter catcB3=
?
?
Dnce an exception is
trown % program control
transfers o!t of te try
bloc) into te catc bloc).
Dnce te catc statement
is exec!ted pgm control
contin!es wit te next
line following te entire
try>catc mecanism.
16
-
7/23/2019 Chapter8 Exception Handling
17/34
xception Handling in
Java
-e can display te description of an Exception in
a println statement by simply passing teexception as an arg!ment.
catc2AritmeticException ae3:
"ystem.o!t.println2Exception#FGae3=
?
o>p
Exception#java.lang.AritmeticException# >by
,ero
17
-
7/23/2019 Chapter8 Exception Handling
18/34
Common Trowable
metods
get$essage23= All trowable objects can ave an
associated error message. Calling tis message will
ret!rn te message if one present.
getocali,ed$essage23= gets te locali,ed version of
error message.
print"tac)Trace23= sends te stac) trace to te system
console. Tis is a list of metod calls tat led to te
exception condition. 0t incl!des line n!mber and file
names too. 7rinting of te stac) trace is te defa!lt
beavior of a r!ntime exception wen ! don9t catc it
o!rselves.
18
xception Handling in Java
-
7/23/2019 Chapter8 Exception Handling
19/34
catc2Aritmetic xception e3:
"ystem.o!t.println2e.get$essage233=
>>e.print"tac)Trace23=
?
o>p# #IJAA7K$"Ljava x
> by ,ero
catc2Aritmetic xception e3:
e.print"tac)Trace23=
?
#IJAA7K$"Ljava x
o>p#
java.lang.Aritmetic xception# > by ,ero
at x.main2 x.java#M3
19
8se of get$essage23 andprint"tac)Trace23
xception Handling in Java
-
7/23/2019 Chapter8 Exception Handling
20/34
xception Handling in Java
$!ltiple catc "tatement
some cases% more tan one exception co!ld be raised by
a single piece of code.
s!c cases we can specify two or more catc cla!ses%
eac catcing a different type of exception.
wen an exception trown% eac catc statement is
inspected in order% and te first one wose type matces
tat of te exception is exec!ted.
After 1 catc statement is exec!ted% te oters arebypassed and exec!tion contin!es after te try>catc
bloc).
20
-
7/23/2019 Chapter8 Exception Handling
21/34
xception Handling in
Java
class Ex:p!blic static void main2"tring
args;len=int c;
-
7/23/2019 Chapter8 Exception Handling
22/34
xception Handling in
Java
0n m!ltiple catc statement exception s!bclassesm!st come before any of teir s!perclasses.
eca!se a catc statement tat !ses a
s!perclass will catc exception of tat type pl!s
any of its s!bclasses.T!s a s!bclass wo!ld never be reaced if it
came after its s!perclass.
!rter java compiler prod!ces an error!nreacable code.
22
-
7/23/2019 Chapter8 Exception Handling
23/34
xception Handling in
JavaNested try statementtry statement can be nested
class x:
p!blic static void main2"tring dd;len=
"ystem.o!t.println2a3=
try:
if2len&&13
len&len>2lenlen3=
if2len&&'3:
int c;
-
7/23/2019 Chapter8 Exception Handling
24/34
E#IJAA7K$"Ljava Ex
java.lang.AritmeticException# > by ,ero
at Ex.main2Ex.java#M3
after catc
E#IJAA7K$"Ljava Ex '+
1+
java.lang.AritmeticException# > by ,ero at Ex.main2Ex.java#153
after catc
E#IJAA7K$"Ljava Ex '+ 4+
6
Array indexjava.lang.Array0ndexD!tDfo!ndsException# 1+
after catc
24
xception Handling in Java
-
7/23/2019 Chapter8 Exception Handling
25/34
xception Handling in
Java
trow
0t is possible to trow an exception explicitly.
"yntax#
trowTrowable0nstance
trowable0nstancem!st b an object of type Trowable or a
s!bclass of Trowable.
y two ways we can obtain a Trowable object
1. 8sing parameter into a catc cla!se
'. Creating one wit new operator
25
-
7/23/2019 Chapter8 Exception Handling
26/34
xception Handling in
Java
class trow*emo:
p!blic static void main2"tring args;
-
7/23/2019 Chapter8 Exception Handling
27/34
#IJAA7K$"Ljava trow*emo 5
java.lang.NegativeArray"i,e xception#
0llegal Array si,e
xception in tread BmainB
java.lang.NegativeArray"i,e xception#
0llegal Array si,e
at
trow*emo.main2trow*emo.java#1P3
27
xception Handling in
Java
-
7/23/2019 Chapter8 Exception Handling
28/34
xception Handling in
Java
trows
0f a metod ca!sing an exception tat it doesn/t
andle% it m!st specify tis beavior tat callers
of te metod can protect temselves against
te exception.
Tis can be done by !sing trows cla!se.
trows cla!se lists te types of exception tat a
metod migt trow.
orm
type metodname2parameter list3 trows
Exception list
:>>body of metod? 28
-
7/23/2019 Chapter8 Exception Handling
29/34
xception Handling in
Java
import java.io.Q=
class Trows*emo:
p!blic static void main2"tring args;
-
7/23/2019 Chapter8 Exception Handling
30/34
xception Handling in
Java
finally
0t creates a bloc) of code tat will be exec!ted after try>catc
bloc) as completed and before te code following try>catc
bloc).
0t will exec!te weter or not an exception is trown
finally is !sef!l for#
RClosing a file
RClosing a res!lt set
RClosing te connection establised wit database
Tis bloc) is optional b!t wen incl!ded is placed after te last
catc bloc) of a try
30
-
7/23/2019 Chapter8 Exception Handling
31/34
xception Handling in
Java
orm#
try
:?
catc2exceptiontype
e3
:?
finally
:?
finally
finally
Catch block
try block
31
-
7/23/2019 Chapter8 Exception Handling
32/34
xception Handling in
JavaCreating o!r own Exception class
or creating an exception class o!r own simply
ma)e o!r class as s!bclass of te s!per class
Exception.
Eg#
class $y xceptionextends xception:
$y xception2"tring msg3:
s!per2msg3=
?
?
32
-
7/23/2019 Chapter8 Exception Handling
33/34
xception Handling in Java
class Test$yException:
p!blic static void main2"tring args;2float3y=
if2,O+.+13:
trow new $yException2Btoo small n!mberB3=?
?catc2$yException me3:
"ystem.o!t.println2Bca!gt my exceptionB3=
"ystem.o!t.println2me.get$essage233=
?
finally:
"ystem.o!t.println2Bfrom finallyB3=
?
?
?
33
-
7/23/2019 Chapter8 Exception Handling
34/34
#IJAA7K$"Ljava
Test$y xception
ca!gt my exception
too small n!mber
from finally
D>7#
xception Handling in Java