Exception handling and throw and throws keyword in java.pptx

shikhaverma566116 139 views 37 slides May 20, 2024
Slide 1
Slide 1 of 37
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37

About This Presentation

exception handling in java


Slide Content

⦿ Th e Exception Handlin g in Jav a i s o n e of the p o wer f ul m e chanism to han d l e t h e ru n time er r ors s o that nor m a l flow of the application can be maintained. ⦿ w e wil l lear n ab o ut Java exceptions, its ty p e an d the di f fe re n ce b etwe e n checked and unchecked exceptions. ⦿ Dictionar y Meaning: Exception i s an abnormal condition.

⦿ Th e core adv a ntage of e xcepti o n han d lin g i s to maintain the norma l flow of the application .

⦿ Su p p o s e the r e ar e 1 state m e n ts i n your progra m an d t h ere occurs a n e xcepti o n a t stateme n t 5 , the re s t of t h e code will not b e e xecut e d i . e. state m e n t 6 to 10 wil l not be ex e cuted . ⦿ I f w e per f orm exception han d ling , the r e s t of t h e state m e n t wil l b e e xecut e d. T h a t i s wh y w e use exc e p t io n han d ling i n Java .

⦿ Checked Exception ⦿ Unchecked Exception ⦿ Error

1 ) Checked Exce p tion T he c l as s es w h i ch d i r e ctly i n h e r i t T hro w abl e c l as s exce pt Runt i meE x cep t i o n an d E r ror a r e k n o w n a s c h ecked exce p t i o ns e. g . I OExce p t i o n , S Q LEx cep t i o n e t c Checked exceptions are checked at compile-time. 2 ) Unch e cke d E x c e p t ion The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. 3 ) Er r or E r ror i s i r r eco v e r able e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

⦿ Except i on ha n dl i ng allo w s us to c ontrol the normal fl o w of the progra m b y us i ng except i on handl i ng i n p r ogra m . ⦿ I t throws a n excepti on when e ve r a ca l l i ng method encounters a n er r or prov i d i ng that the cal l i ng method takes care of that er r or. ⦿ I t als o g i ve s us the scop e of o rgan i z i ng and d i ff e r e nt i at i ng betw e en d i ff e r e nt er r or types us i ng a s e parat e bl o ck of co d es . Th i s i s d o ne w i th t h e help of tr y - catch bl o cks

T h e r e ar e giv e n som e sc e na r io s wh e re unc h eck e d e xcepti o ns may o c cu r . T h ey ar e a s follow s : 1 ) A sc e na r i o wh e re Arit h m e ticException occurs I f w e divid e an y n umber b y zero, there occurs an ArithmeticException. int a=50/0;//ArithmeticException

2 ) A sc e na r i o wh e re NullPoi n te r Exception occurs If we have a null value in any variable , perf or m in g an y ope r ation on the variable throws a NullPointerException. Strin g s = nul l ; System.out.println(s.length());//NullPointerEx ception

3) A scenario where NumberFormatException occurs The wron g formatt i ng of an y value may occur NumberFormatException. Supp o s e I have a str i ng var i abl e that has character s , convert i ng th i s var i abl e i nto d i g i t w i l l oc c ur NumberFormatE x cept i o n . Str i ng s= " ab c "; int i = Integer . pa r se I n t ( s);/ / Num b erFormatE x c ep tion

4 ) A sce n ari o wh e re ArrayIndexOutOfBoundsException occurs I f yo u ar e ins e rting an y valu e i n the wrong in d ex, i t woul d re s ult in ArrayIndexOutOfBoundsException as show n below: int a[] = ne w int [ 5 ]; a[1 ]=50 ; // Ar r ayInd e xOut O fBou n dsExc epti on

⦿ The JVM f i rs t l y ch e cks whet h er the except i on i s handled or no t . ⦿ I f e xcept i on i s not handled, JVM pr o v i de s a default exception handler that performs the fol l ow i ng ta s ks: ⦿ Prints out exception description. ⦿ Pr i nts the stac k trace ( H i er a rchy o f m ethods where the exception occurred). ⦿ Causes the program to terminate. ⦿ Bu t i f except i on i s handled b y the application programmer, normal flow of the application is maintained i.e. rest of the co d e i s ex e cuted.

⦿ This small program includes an expression that intentionally causes a divide-by-zero error: cla s s Exc { publ i c stati c v o i d main ( Str i ng arg s [ ] ) { i nt d = ; i nt a = 4 2 / d ; } } W hen the Java run - time sy s tem detect s the attemp t to d i v i de b y ze ro, i t construc t s a new exception object and then throws this exception. Th i s cause s the execut i on of Exc to st o p, becau s e once a n ex c ept i on has bee n thro w n , i t mus t be c aug h t b y a n excep t i o n ha n d l er an d dea l t w i th immediately

⦿ Sta c k Tra c e i s a l i s t of method c a l l s fr o m the point when the application was started to the poi n t whe r e the exc e ption w a s t h r ow n . The most re c ent me t hod c a l l s a r e a t the top. ⦿ A sta c k tra c e i s a v ery h e lpf ul debuggi n g tool. I t i s a l is t of the me t hod ca l l s that the appl i cati o n wa s i n the mid d l e of w hen an Exc eption wa s t h r ow n . ⦿ This i s v ery use f ul be c au s e i t doe s n't o n l y s h ow yo u w he r e the er r or happe n ed, bu t al s o how the progr a m ended up i n that pla c e of the code.

⦿ I n som e cas e s , more than one exc e pt i on could be raised by a single piece of code. To handl e th i s type of s i tuat i on, yo u can sp e c i fy t w o or mo re catch cla u s e s , each catch i ng a d i ff e r e nt type of except i on. ⦿ W h en a n except i on i s thrown, each catch stat e ment i s i nsp e cted i n order, a nd the f i rst one whose type matches that of the except i on i s ex e cuted. Aft e r one catch st a tem e nt ex ecute s , the other s are bypassed, and execution continues after the try/catch block.

⦿ I n som e cas e s , more than one exc e pt i on could be raised by a single piece of code. To handl e th i s type of s i tuat i on, yo u can sp e c i fy t w o or mo re catch cla u s e s , each catch i ng a d i ff e r e nt type of except i on. ⦿ W h en a n except i on i s thrown, each catch stat e ment i s i nsp e cted i n order, a nd the f i rst one whose type matches that of the except i on i s ex e cuted. Aft e r one catch st a tem e nt ex ecute s , the other s are bypassed, and execution continues after the try/catch block.

Arithmetic Exception occurs rest of the code

⦿ At a time only one exception occurs and a t a time only one ca t ch bl o ck is executed. ⦿ All catch block s m u s t b e o r d e r e d f rom most specifi c to m ost g e n eral, i . e. ca tch for Arith m eticExcepti o n must come befor e cat c h for E xcepti o n

⦿ The try statemen t c a n be neste d . That i s , a try statement can be inside the block of another try. Eac h time a t ry statemen t i s entere d , the context of that excepti on i s pu s hed on the stack. ⦿ I f a n inne r try statemen t d o es not have a c a tch handler for a particular exception, the stack is unw ound an d the next try statement’ s cat c h hand l ers ar e i nspe cted for a ma t ch. ⦿ Th i s continu e s unti l one of the ca t ch statements succeeds, or until all of the nested try statements are exh a uste d . I f no c a tch state m ent ma t c h es, t h en the Ja v a run - time s y st e m w i ll hand l e the excepti on

⦿ Jav a finally bloc k i s a bloc k that is used to e xecute importan t code such as closing conn e cti o n, strea m etc. ⦿ Java finally block is always executed wh e ther exc e p t io n i s h andle d or not. ⦿ Java finally bl o ck follows try or ca tch block.

⦿ For each try bloc k th e re can b e z e r o or more catch blocks, but only one finally block. ⦿ Th e fi n all y bloc k wil l not b e e xecut e d if progra m exits( e ithe r b y calling System.exit() or by causing a fatal error that causes the proces s to abort ) .

⦿ The Java throws ke y w o rd i s us e d to declare a n except i on. I t g i ve s a n i nformat i on to the progra m mer that the r e may oc c ur an except i on s o i t i s bette r for the progra m mer to provide the exception handling code so that normal fl o w can be ma i nta i ned. ⦿ Exception Handling is mainly used to handle the checked except i ons. I f there oc c urs an y unchecked except i on such as NullPointerException, it is programmers fault that he i s not perform i ng c heck up before the code being used.

Syntax of java throws retur n _ty p e m e thod_ n ame ( ) throws exc e pt ion_class_name{ //method code } unchecke d Exception : und e r you r control s o correct you r code. error : beyon d you r control e . g. yo u are unable to do anything if there occurs Virtual M achine Erro r or StackOverflowError

⦿ Now C h ec k ed Exc e ptio n can be pro p agate d (fo r warde d i n call stack ) . ⦿ It provides information to the caller of the m e thod abou t t h e exc e ption
Tags