0% found this document useful (0 votes)
49 views

Java 3 Unit

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
49 views

Java 3 Unit

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
lL EXcePTiION HANDLING AND MULTITHREADING IN JAVA 3.1 | EXCEPTION HANDLING IN JAVA The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc x 3.1.1 What are Exceptions In Java, exception is an event that occurs during the execution of a program and disrupts the normal flow of the programs instructions. Bugs or errors that we don’t want and restrict our program's normal execution of code are referred to as exceptions. Example of Exception ExceptionExamplejava import java.util. Scanner, public class ExcptionExample { public static void main(String args{]) { Scanner sc = new Scanner(System.in); ‘System out print(‘Enter a number: " int number = sc.nextint(); ‘System.out.printin(“You have entered: "+number); } } Let’s run the above program and enter a float value deliberately to generate an exception. ‘TATA PUBLICATIONS Se Enter a number: 9.0 Exception in thread “main java. ut inputMismatchExcopin 2 ja vasetjava tl Scanner trout {Scanner java 509) teva baseljava th Scanner nent(Scanne av 594) A) at java.basejava uti Scanner nentil(Scannetave:2258) leva basefava. ut Scanner nentinl(Scanner|ava:2212) ‘at ExcpionExample main(Excption Exemplejava:8) I shows the InpuiMismaichExaception. Because the program accepts an integer 8) value. We observe thatthe next statement is skipped and the program is terminated, Advantages of Exceptions It separates error handling code from regular code. 2. Ithas the ability to propagate error reposting up the call stack of methods, 3 The grouping or categorizing of exceptions is « Ratural outcome of the clisg hierarchy. Java Exception Keywords i Java provides five Keywords that are used to handle the exception The following table describes each ee [Lieeyrora Description | #7 | the ey keyword is wed to spare Bak whew we A) should place an exception co ode. It means we can't use tty. block alone. The tr block must be followed by. Types of Exceptions Exceptions can be categorized into two ways Builtin Exceptions i) Checked Exception ii) Unchecked Exception User-Defined Exceptions — Built-in Exception dy available in Java libraries are referred to as builtin eptions that are alren 2 tio aeiams ee re able to define the error situation 60 that we Gib ‘ier Gc or Bally exception. These exceptions a a ’ an 1e reason. of getting this error. ft can be catege must be preceded by try block which means pe cen 9" . sompile-tim {te cach block alone. can be followed by finally block 1. Checked Exception: Checked exceptions are called nie in = because these exceplionsareshecked at compile ‘not. The progeammer Tray | Te tray Wockm walioeamae whether the progranmer andes te exception or not The rPmranunet EIEIO Us exci whether an oye should have to handle. theexcepion: otherwise, the syste ee ‘compilation error. e wn as Unchecked hi Tie thee heya tw a apo 4 Exceptions: Ruime cepon area known. Uneecd one | The “throw keyword tras en __ | 2. Uncheeked Except ni are not checked at compile-time 60 ¢9 speciion that there may et '© declare exceptions, Exceptions. These exception hhas handied them or not but it's the Method. does taney et" ception nthe not check whether pions and provide a safe th myethod signature 8” %*Ption Ii always used esponsibility of the programmer exit. i fit t<< = | B) User-defined Exceptions User Defined Exception or custom exception is creating YOUr OWN exception ca. on W Keyword. Tis can be done by extending je ‘nd throws that exception using ‘throw’ keyword class Exception. There is no need to override any of the above methods available inp, Exception class, in your derived clase, But practically, you will require some amouny g¢ customizing as per your programming needs. 3.4.2 Writing Your Own Exception Classes You can create your own exceptions in Java, Keep the following points in ming when writing your own exception classes 1. All exceptions must be a child of Throwable. 2. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class 3. If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below. class MyException extends Exception ( ) You just need to extend the predefined Exception class to create your own Exception. These are considered to be checked exceptions, The following InsufficientPunds Exception class isa user-defined exception that extends the Exception class, making ita checked exception. An exception classislike any other class, containing useful fields and methods 3.1.3. Try, Catch, Throw, Throws Clauses The below keywords are used in Java for Exception handling 1 Ty Catch Finally AWA PROGRAMMING Java Exception Keywords Java providesfive keywords that ae frie dexter ee used tohandle the exception, The following Keyword eel a Description 7 Tey keyword sed pay a ck whe we should pe om Selon mare we cat ey Hak ne Tey Hes catch | The ‘calchblock sed fo andl the eaception I mus fe preceded try block which means we ca se cath block lone can be flowed 2) ialy Hock later ‘anally | The" finaly blocks used wo execute he necessary cde of the pregram. Inf executed whether an exception shan or nok Throw | The"thron” keywords usedte throw an exepion ‘rows | The 'hrovs! keyword ie wed to declare exceptions, It specie tat there may occur an excepton ‘in the methed. 1t doesnt thw an ecception. tis alway used with metho signature. ‘Try Block In Java Whenever we are writing a program there could be acode that w throw an exception. For example, we might suspest that there might be zero” operation in the cose that will throw an exception. is enclosed in abl ‘This code that might raise an exception is encl “ So the try block contains the code or set of statements thal fe that we suspect might division by lock with the keyword “try” ‘can raise an exception. ‘The general syntax of te try block is as follows: ty ‘get of statements that can re oxcetion nts will raise exceptions, then a ton occuvat eps cya programmer thinks that cetain statements ceo reeset ary Bese Neate statement in a try block, then the reat. ofthe cout nn a somoccursin a ey Wockat «parila satement en 6 When an ce verte abel. To prevent SSOP ack comes oe fade gees Dae es rer atch block following i. keyword, So a try blockalways has 2 ¢ @ ‘TATA PUBLICATIONS Bea — Hien a ee 2. Catch Block In Java We use a catch block to handle exceptions. This is the block with the “cajchy Keyword. The catch block follows the try block. Whenever an exception occurs in the try block, then the code in the catch boc that corresponds to the exception is executed. The general syntax of the catch beck is catch (Exception e) eode tohandie exception © y Generally, the declared exception must be the parent class of all exceptions, i¢ 1 we can also write specific exception Exception. But if there is more than one except types or generated exceptions. 3. Try-Catch Java The general syntax of the try-catch block is shown below: try code causing exception } ‘catch (exception (exception type) @ (object) « exception handling code ) The try block can have multiple lines of code that can raise multiple exceptions Each of these exceptions is handled by an independent catch block. The generic exception handler, object e of Exception class can handle all the exceptions but if we want to handle specific exceptions, then itis advisable to specif the generic exception handler as the last catch block. r 4, Throw An Exception In Java Java provides a keyword “throw” using which we ; 8 it i tr ti th a ey a toraise someexceptions after checking operands wecan doso using the throw” keyword Using the throw keyword, we can throw the checked a The throw keywords also used to throw custom exceptions nce MEP ea tnruarcnrion he general syntax of the throw keyword iy; tnrow exception, throw new exception_cless(ertormossage”) 5. Throws Clause We have seen try black to declare exceptions. Itcontains the code that may raise There is another way to declare an exception and itis using the “throws exceptions keyword. The declaration of exception using the “throws” keyward tells the programmer that there may be an exception specified after the “throws” keyword and the programmer should provide corresponding handler code for his exception toma the normal flow of the program. However, the question arises as to why we need a “throws” keyword when we have a more reliable try-catch block to declare and handle exceptions? One reason is as the number of exceptions that might possibly occu the namber of catch block that handles exceptions also increases as one catelrblock can handle only one exception. Simvaty if there are many mahodsina program and each method asnumeross exceptions then the code wil become unnecessarily long and unmanagta rhrows keyword in the method signature and sch seems to be a viable solution. Thus declaring an exception with # then handling the method call using ty-<2 3 using throws keyword is that we are laring exceptions ode are provide a handler fora declared exception Another advantage i “ ‘do net provi forced to handle the exceptions Ife then the program will ais a erat tax ofthe throws Keyword asset follows The general sym etun_typa mata tows exc timethod code 1 ge ee eee BA To 3.4.4 Difference between checked vs. Unchecked Exceptions Difference Between Checked and Unchecked Exception SNo Crate Racca Unchecked Exception 1, | These exceptions are checked at compile | These exceptions are just opposite time. These exceptions are handled al | the checked exceptions, Thege exceptions are not checked and handled at compile tin direct subclasses of the These exceptions are direct subdasses of | They are th exception but not extended from | Runtime weption class Runtime xception clas, The code gives « compilation error in the | The code compiles without any error case when a method throws a checked | because the exceptions escape the notice of the compiler. These exceptions are the results of user exception. The compiler is not handle the exception on its own. ‘created errors in programming logic ‘4 | ‘These exceptions mostly occur when the | These exceptions occur mostly due | probability of failure is too high. toprogramming mistakes, Common checked exceptions include | Common unchecked exceptions TOException, _DataAccessException, | include AvithmeticEseeption, InterruptedException, etc. y InvalddClassE ception, NialfointerEsception, ete 6 | These exceptions are propagate! using | Thess anv sutomatically propan the throws keyword, aes It is required to provide the try-catch | In the case of unchecked excepiion It and tey-finally block t0 handle the | isnotmandaon checked exception, 3.1.5 Error Vs. Exception Exceptions and errors both are subslasses of Throwable 4 problem that manly ours du othe lack ofsystem resources and aa applclien should not catch these types of problems: Some ofthe examples of ervors ax syst crash error and out of memory ervor. Errors mostly occur : to-an unchecked type The error indicates at runtime that’s they belon Exceptions are the problems which can occur at uke Ur at runtime and compile time. Hii the Code within by thd dev oper Har ins ave cic RO such as checked exceptions and unchecked excentin categories pu ciitd wr prcorcmaio Key kee Tee | Ghaiiwageiaiare Package It belongs to jav = Recoverabe/ | Wisinecoveie Inrecoverabl Were Weartbe accra compile Team oscer at ran tne comple tine QuorMemoinacIOFeer | NallfinedtScepton SaExcpion Example of Error public class ErrorExample ( public state vold main(String] args recursiveMethox!0) ) public static void rcursiveMethodit witet!=0 recursiveMetha ) ) ) Output Exception inthread “ain” Jave.ang StackOver at Error xemple.ErorExample(Main ava:42) Example of Exception public class ExceptionExample{ public state void main( Stina] arasX intx = 100; imy=0; flow intz=xtye ) ) Joyz00 Jave.tang Aaithmaticéxcention : samo meine xcepenexae 07 ee eam ALExceptionE» TATAPUBLICATIONS. Bea SR 6 [32 ] MULTITHREADING IN JAVA THRED AND ITS LIFE Cycjg ‘A thread is a lightweight sub process. It isa separate path of execution becayy each thread runs in a different stack frame. A process may contain multiple threags Threads share the process resources, but stil, thay execute independently. Multithreading in javaisaprocssofexecting wo or more threads simultangoudy tomaximum utilization of CPU. Maliteaded applications ute two oF mors trea, Fun concurrently, Hency, itis also known as Concurrency in Java, Each theead rie Parallel to each other. Multiple threads don’t allocate separate memory area, hen they save memory. Also, context switching between threads takes less ime, Example of Multi thread Package demotest; Public class GuruThread! implemerts Runnable { Public eatic void main(String args) ( Thread guruThreadt = new Thread(Gunst) Thread guruThread2 = new Thread(’Guni2) guruTiveadt stant) guruThread2.start(); System out pritin("Thread names are following: ‘System out pritin(guruThreadt getName()) SSystem.out printn(guruThread2 getName()) ) @Override public voigrung) { ) Advantages of Multithreading Multithreading programming has the following advantages ee S JAVA PROGRAMMING Manes allows an application ‘Program to be always reactive for input, even already running with somebeckgraed vet, Multithreading alk lows the faster execution independently of tasks, as threads execute Multithreading provides better utilization of cache memory as thwads share the Maltithreading reduces the numberof therequired server as one sever can execute multiple threads ata tine. Thread Life Cycle in Java The Lifecycle ofa thread New Wane | Running Stages of Thread Life Cycle in Java There are various stages of lifecycle of thread as shown in above diagram: New Runnable 1 2 3, Running 4. Waiting 5 Dead — js created using class “1 ss 2. New: ln this phase, ne ris also Known a bor thread rogram stars this tate tl Fhe ad is inve Jked with a startmethod. The thread con gun scl scheduler, whether to run thet eS = ean eares a ee ==" | 7 aS Eee Running: Whenthethreadstarts executing then he sate S haPH=A 10“ State. The scheduler selects one thread from the thread pool, ci, in the application, ting: This is the state when a thread has to wait. As there multiple threag, are running in the application there is anes for syucwonization between threads Hence, one thread has to wait, till the other thread gets executed. Therefore, i, state is roferred as waiting state Dead: This is the state when the thread is terminated. The thread is in running state and as soon asit completed processing itis in “dead stat 3.2.1 How to create threads In java, a thread is lightweight process Every java program executes bya threa called the main thread, When a java program gets executed, the main thread created automatically. All other threads calle from the main tread, The java programming language provides two methods to create threads, and they are listed below. 1 Using Thread class (by extending Thread class) 2 Uisng Runnable interface (by implementing Runnable interface) Let's see how to create threads using each of the above. 1 Extending Thread class The java contains a builtin class Thread insce thejava.lang package, The Thread class contains all the methods that are related tothe threads To create a thread using Thread class, follow the step given below. Step-1: Create a class as a child of Thread class. That means, create a cass tha! extends Thread class, Step-2: Override the run() method with the code that isto be executed by th thread. The run() method must be public while overriding. Step-3 Create the otject of the newly created class in the main() method Step-4: Call the start) method on the object created in the above step. ————— tarapusvearon? Example lass SomploThvoad extends Teac, public void run) ‘System out pnt Threads unier Ruring forlinti= 4; i=t0:144)¢ System out printntt=*+ ) public class My Thread, Test{ public static void main( Stina] args) ‘SampleThreed t= new Sampletivead() ‘System. cut pintin( Thread about to ster.) tsar); When we run this code, it produce the following output 1 gunse dase MyTeT ( sca TATA PUBLICATIONS —— | oe 2. Implementng Runnable interface able inside the javalang package, thy The java contains a builtin interface Runa Jass that contains all the methods ty, Runni le interface implemented by the Thread are related to the thread. To create a thread using Runnable interface, follow the step given below Step-1: Create a class that implements Runnable interface Step-2: Override the run( ) method with the code that is to be executed by thread, The run( method must be public while overriding Step-3: Create the object of the newly created class in the main( ) method. Step-4: Create the Thread class object by passing above created object as parameter to the Thread class constructor. ‘Step-5: Call the start() method on the Thread class object created in the above step. Example class SampieThread implements Runnable( publi void rund) { ‘System. out pritin("Thread is under Running.) for(int = 1; i<=10; i++) ‘System.out printin('= “+ public class My Thread Test { public static void main(String) args) ( ‘SampleThread threadObject = new SampleThread() ‘Threadthread= new Thread\threadObjec) Systom.out.prntin( Thread about to stat.) thread stat) pete aah! ane a pe rararusLcarons When we run this code it produce the falowing output ‘class Swolethvead inplemnts Runnate( oS oder tuning. }y T's public votd run) Systeme petnla "Tread fortint tes te to) Syste. ovtprtine dS * + 4) > > > public clase Wy Teod Tost { 1 sre) “agli Sonpletire 3.2.2 Thread Class in Java rads for tasks aciors for erating thre In Java, Thread. ass. conain enyeralconsrucor for eating Sane a isegt idle aang a mee he Thuead Each thread i J ted and controlled by a unique object of the ach thread in Java is eat - Gh: an oes of aed ert ea IC SPST emainvariousmetnodehat canbe wsedta sta con ETE nase a ear it Wed rented activism SEED 1 execution ofa thread ® ents Runnable interface. The sve doo xine bet cums and # DTI declaration of thread class ss fotlows Public lass Thread extends Object implements Rusneb!® fi eee ‘TATA PUBLICATIONS: ———e—S—“‘“‘C:;*—“—F FC 3.2.3. Use of Synchror to any shared resource Java Synchronization is better only one thread to access the shared resource, Si Syntax: Public final native boolean isAlive) join(): The join() method is used to make a thread wait for another thread ferminate its process. The general syntax is 7 Syntax Public final void ping tnrw interrupted xcoption tc block. method is used to stop the thread. The general form for this method This method throws InteruptedException and must be used within atry-« stop (: Thi Syntax: public final void stop() This method neither accepts anything norretums enything. suspend(): The suspend() method is used to suspend or pause a thread, syntax: pub final void suspend) resume(): This method is used to resume the suspended thre: “Sel lela the suspended thread, It neither accepts syntax; public final void resume() isDaemon(): This m jor Is used to check the thread is daemon thread or not. Syntax: public final boolean isDaemont) ed Keyword” tpl , ton in Java i the capability to contol the access of muikiple threads were we want to allow Why use Synchronization? The synchronization is mainly used to fo prevent thread interferences To prevent consistency problem. - iment ty ‘aT PUBLICATONS JAVA PROGRAMMING types of ronization There ate two types of synchronization 1, Process Synchronization Thread Synchronization 32.4 How to Avoid Deadlock In Java, a deadlock is programming situation where two or more threads are blocked forever. A deadlock condition wl occur with atleast two threads and two or In the thread, each object has a lock. To acquire a lock, Java provides synchronization to lock a method or code bloc Itallows that ata tme only o 5s that method. Nevertheless, ifa thread wants toexecutea synchronized method ead + first tries to acquire a lock, Itispossblethat another thread has already acquired that lock then the thread (that wants to acquire the lock will have to wait until the previ thread does not release the lock. How to avoid deadlock in Java? ‘though it snot possible to avoil deadlock condition but we can avoid i PY using the following ways 14 use locks only for those members on Teads fo a dendlock situation! We Keep your code 1. Avoid Unnecessary Locks: We shoul Unnecessary use of lo ince data structures If posse, fed ArrayList use which it is required end you to.use 2 ockt example, free form locks. For the ConcurrentLinkedQuev®: instead of using synchronize jeadlock is to avoid giving a lock to avoid d read. Since we Another Way i diy provided a lock to one th nave ale sc to multiple threads. 2. Avoid Nested Lod le threads if we allocating le“ ) Metho« to mip rust avoid ee gvoncan et deni it head ae DE 3. rng Tred nn I och thee is to use join with the maximum time ae ies to fish ifs aways Da i a ae wait for the! ‘thread to finish. TATAPUBLICATIONS _ ae aneaoe ener ing: Always assi ic value to each lock. Before acquiring Use Lock Ordering: Always assign anumeric va 0 the lock with a h et numeric value, acquire the locks with a lower numeric value. Lock Time-out: We can also specify the time for a thread to see thread does not acquire a lock, the thread must wait for a specific retrying to acquire a lock. What are exceptions? writing your own exception classes. Write about try, catch, throw, throws clauses. Difference between checked vs uncheckedExceptions. Write about Error Vs. Exception. Explain about Thread and its Life cycle. Write program for how to create threads, Explain about Thread class in java, use of synchronized keyword. What is dead lock ? How to avoid deadlock?

You might also like