0% found this document useful (0 votes)
15 views23 pages

Java 3rd Units

The document discusses various exception classes in Java, including ArithmeticException, ArrayIndexOutOfBoundsException, and NullPointerException, detailing when they are thrown. It explains the structure of exception handling using try, catch, and finally blocks, and emphasizes the importance of handling exceptions to maintain normal application flow. Additionally, it covers the use of the throw and throws keywords for explicitly throwing exceptions and declaring potential exceptions in methods.

Uploaded by

payalsaini26905
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
15 views23 pages

Java 3rd Units

The document discusses various exception classes in Java, including ArithmeticException, ArrayIndexOutOfBoundsException, and NullPointerException, detailing when they are thrown. It explains the structure of exception handling using try, catch, and finally blocks, and emphasizes the importance of handling exceptions to maintain normal application flow. Additionally, it covers the use of the throw and throws keywords for explicitly throwing exceptions and declaring potential exceptions in methods.

Uploaded by

payalsaini26905
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
checked OxcEptions Classes g, on -the following are the common u ae or ‘arithmeticexception 11 thrown, when & Program attemoy tin a by zero. a ee wr ay oe indexout 7Boundoexcors jon : It Is thrown when, a lo to access an index of 27 array that does not exist. Prone 7 my NogativearraySizoExcePtlo” zItis thrown when a progra, i" tive size. atom, bar by, qu an array that has neg ClassNotFoundexception it depends at runtime- . ) stringindexourorBoundsEXxCePton : Itis thrown when a "dy to access 2 character at a non-existent index in a String, Progra, It is thrown when JVM attem, Pts top, wy NullPointerException = operation on an Object that points to null or no data, : Itis thrown when a program i TFAM is atten, ‘NunterFormatException astring toa numerical data type. : It is thrown when a program can Not (iv) on, Pting tg [Link] Error ~ Errors are typically ignored in your code because you can rare} an error. Errors are not exceptions at all, but problems that any = anything yong the ey of the user or the programmer. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineg; etc. Tor, Assert Nn Exception Handling eption handling is managed via five keywords : try, catch, “iTY) Catch, throw, Z 7 th Java exc and finally. A block of statements in which an exception can occur must b keyword try. This block of statements is known as try block. Whi wre ty detected, then the runtime informs the application that an error his = process of informing is called throwing an exception. 38 Secu A catch block defined by the ke! i word catch, catchi bi 28 the, exception thrown try block and handles it appropriately. ty ia io plock that peas an exception must immediately follows the try block i? i rows the excepron. tt oh is used to h ot inal Dr ‘erent ee tna a exception that is not caught by any of the 8 atch Stare z ly block is added immediat ft oe ve ast catch block. = iately after the try block fer an excepti a? qually throw tion, use the keyword throw. In some cases, an | mar nat is thrown out of a method must bi if : | 1° fption t! © specified as such by a throws oY your pry-cateh block js . J 0 am statements that you. want to,monitor for exceptions are contained within a pos _The try block is immediately followed by one or more catch blocks. If an we ion occurs within the try block, it is thrown. Each catch block specifies the oe exception it can catch and handle. yp? of try-catch block is tax | 9 oy { : statements; // code that might generate exceptions // If exception occur, throw exception object } catch { || statements; (ExceptionType exobj) // catch exception object thrown by try, //if its type matches with Exception type // Handles the exception i.e. takes corrective Action } an exception, the program control jumps to the catch ception. When the try block generates satement of the catch block and catch block is executed for handling the ex When no exception is detected, the control goes to the statement immediately after he catch block. [295] Example 11-2 Program to inustrate the tl class exception! ry-caten block. string arest)) public static void main { int x=50, YO intresult=0; try { result=x/Ys #Found Arithmetic Exception // Exception Object is created g [Link] printin ("We are in try block"); thrown catch (ArithmeticException e)/ catching Arithmetic oe ( ; PXcepon [Link] printin("Arithmetic exception occurred”), [Link]-printin(e); ‘ pay [Link] printin(’ "This is the last statement"); Output: Arithmetic exception occurred [Link]: /by zero This is the last statement It is, clear from the above program that the statement having the message. Ti the last statement is executed, but the statement having the message. Weel try block is not executed. The statement [Link](¢): cis description of an exception. 5 an object of o: class Is thrgcPtion own JVM 7. prints out exception desoript - Prints stack trace o"Ption 3, terminates the program FIGURE 11.2 The JVM firstly checks after occuring an exception whether the 7 exception ornot in java program. If exception is not handled, JVM provides cdma handler that performs the following tasks : faultexception e Prints out éxception description. e Prints the stack trace (Hierarchy of methods where the exception occurred). e Causes the program to terminate. But if exception is handled by the programmer, normal flow of the application is maintained i.e. rest of the code is executed. Example 11.3 ofBoundsException. This program illustrates how to handle ArrayindexOut ss 11.4. class exception2 args{) public static void main(String { int al ] = {10, 20, 30}; total=0; uy 3; 1/Found ArraylndexOutOfBoun, tal=a[0] afl }+al2}+al: a Object is created & thrown HAn } catch(ArrayIndexOutOfBoundsException e) { [Link] printin( [Link] printin(e); “You are trying touse an invalid index"), } [Link](""Total Marks :" + total); [Link] ("This is the last statement"); } } Output: ‘You are trying to use an invalid index [Link]. ArrayIndexOutOfBoundsException: 3 Total Marks : 0 This is the last statement Using Multiple Catch Blocks Econ, M5 We can use more than one catch clause in a single try block however every cath block can handle only one type of exception. 2 many Cases, more than one exception could be raised by a single piece of code. In order to handle such a situation multiple catch clauses, each catching a differen exception type can be specified. W “i [208] poe i nl eee erceeion : 1 obj!) CL a 1 sane exceptions of Tye (oe : i2) 2, 00) de oP [] | jy Hlandle exceptions of Type? } i. pee gil cnn ipmtandle exceptions of Typei is throw! catch statements are inspected one by one and the first yon x00? rgumert type matches the exception type is executed. whose 4 7 one for handlers stops once the catch clause is finished. Only ythe matching esearch executes; It's not like a switch statement in which you need a break ise rae a sich oe case tO prevent the remaining ones from executing. after 2201 Cee ee ee ae oN q me Note : \ 4. Ata time only one Exception is occured and at a time only \ ‘one catch block is executed. i 2. Allcatch blocks must be ordered from most specificto most | general i.e. catch for ArithmeticException must come before | \ catch for other exception. | Example 11.4 Program to illustrate multiple catch block. class exception2 { public static void main(String args{]) { int af ] = (10, 20.30); 20 int total+0; ty, { totalcafO}talt}+al2}+0151 Found ArrayIndexOutO#p, ound //An Object is created & thrown XCEDtion, int result=50/0; //Arithmetic Exception, but unreachable } . catch CAxithmeticxception e) //catching Arithmetic Exception Object { [Link](", sities stic exception occurred"); [Link](e); " } catch(AmrayIndexOutOfBoundsException e) { System: out printin(""You are trying to use an invalid Jind, System. [Link](e);~ [Link] printIn("Total Marks : " + total); [Link] printin (""This is the last statement"); Output: You are trying to use an invalid index [Link]. ArrayIndexOutOfBoundsException: 3 Total Marks : 0 This is the last statement [300] Finally Statement | (9 ctatement is used to han b (ech statements. A ip gus a aithin a try block. The finally lock ma a eatch block, NO matior Whar’ wi yes all ids normally or because O ang 4 ns finally. Java finally Block ad . St by 8 eye, the . itch that inclug Wed by 4° Srectteg se vromt of try/eal 8 finally je Y try veo is : aN gy ally block t Mitty code } catch (...) { MW catch code } catch (...)' { Wcatch code M [Link] \ ‘ it to perform use it to per result, we can Sing system xecute AS a rest nd releasing sy Si is guaranteed to e) * siosing files and releasing SY i ra eck - operation] uh closing fles, an house-keeping eee [301] "Sources. ‘ Java finally block Is always executed whether exception Ishandled o- ,., In figure 11.3. ‘exception occurred? finally block is executed FIGURE 11.3 Example 11.5 yy Py Program to illustrate the concept of finally block. class exception] , public static void main(String args[]) int x=50, y=0; ’ intresult=0; © try. { result=x/y; //Found Arithmetic Exception //Exception Object is created & thrown [Link] ("We are in try block"); } c 2 ree em (ArithmeticException _¢ e)// catching Arithmetic Exception object [Link]; -prindn("Arithmeti i ") ; System. ont printi(e) —F ewe ena l. ial { [Link] Print Fea py. ckig [Link]('' This j YS Fy J ajemnout P *SUhe lasts, me on nt"), y { i ("fc exception occured os mene hmeticEXception; Ioy zero fe oa lock is Always Executeq je 11-6. al j finally exam 3 508 the java ly le where NO catch ue Statement ie i { public static void main(String args[]) {sat x=50, y=0; jntresult=0; ty result=x/y; Found Ari } finally { } [Link] printIn(""This is the last statement"); [Link] printin("Finally Blockis ‘Always Executed"), } } Output : Finally Block is Always Executed : cPtion in thread "main" [Link]: /by 2° [Link](chap1 15 .java:9) 1303) : Using Nested TTY Block The try block within 2 TY block Is known as nested try block in java, er ptock may cause ONE OrrOF aN th met tion may arise where & Pe ote, isel! nay enue another error In such class: Se ages have to nti Ifthe innermost try statement does NO! have a ING Catch stator, Mag yer try statement are inspected for a m; Mens 2d. the catch handler of the UPP arent ty : if no catch stateme! h continues till all the try’s a7 exhausted. nt matengn 2 = java run-time system will han + then z Syntax is { try statements ty { inner try statements } catch(Exception e) { } } catch(Exception e) { 447 if foo inustrate the concent 4 n fo RSteq i o ic void main(Sty { puesto no ‘ Ng argsty gy { intx = 50/0; } sities cateh(AnithneticBcentig, °) { Systemout printing, } : c intal]=new a(S] = 10; } caich(ArrayIndexOuro, : i "Boundstceon °) int{4); [Link] printin(g); [Link]¢ } ? "Remaining Statemenis" catch(Exception e) } [Link] printin "Exception handeled "); } [Link]-printin("The ‘Last: Statement"); } Output: peh&-ArithmeticException: /by zero Walang, 'yIndexOutOfBoundsException: 5 wining Statements TheLast§ . tatement [305] 1.5.2 Using Throw Keyword tions thrown by thy il been catching except ae satel weyword is used to explicitly throw aN Sxception, van a checked or unchecked exception Le usi heats emus. nme i lo m an ex Therefore, throw keyword is usec 10 exception find the appropriate oon. ceee Now ‘Steate as meen To throw statement. Mediat Sow sitcnent any subsequent statements are not exec ely g, 2 ‘uted, tops nc Byorax is : a oar throw instance ; where instance is an object of type Throwable. Commonly, a ne used to create an instance. We can also create a Throwable parameter into a catch clause. Example 11.8 (a) throw new ArithmeticException( ); (b) throw new NullPointerException( ‘4 In example (a), the throw statement is manually throwing Arithmetic) example (b), the throw statement is manually throwing NutlPointeres on, Example 11.9 Ption, In this example, we have created the validate method having integer para age is less than 18, we are throwing the ArithmeticException otherwiss im ter, © Printa, te class ExceptionS static void validate(int age) if(age<18) hee TOW NeW ArithmeticException("Not Valid To Vote); else ? 5 [Link]("Welcome to Vote"); public static void main(String agrs[]) validate(15); [Link]("Last statement"); } Output : Exception in thread "main" n Y [Link]. Arithmeti ion: spe at [Link](chap!17 jane) en ne PHIM: Not valid TO at [Link](chap | 17,java:12) owing 8M Exceptig, if caught BY One cate P Rethrowing an exo, b, a catn g handler can take cetlon i io - , care of another. Sof ® 0" es ; on mm ieee wok 8) i” a »y { th in is A Towe, “iy ng th ' row is a keyword. 3 Sean f° tion which we wan ns exe? tito ethrow, ’ 9 41.10 tig ga da { iplic static void Exceptio, - (= (3,6 Br Generate int al] = (3, 6,9, 12,1 i int BL = 3,0, 6,0,8)," 8h ; for (int x = 0; x

You might also like