Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling Visit for more Learning Resources.

Similar presentations


Presentation on theme: "Exception Handling Visit for more Learning Resources."— Presentation transcript:

1 Exception Handling Visit for more Learning Resources

2 Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide by 0 we terminate abnormally. Exception handling gives us another opportunity to recover from the abnormality. Sometimes we might encounter situations from which we cannot recover like Outofmemory. These are considered as errors.

3 Hierarchy

4 Hierarchy Throwable class is a super class of all exception and errors. Exceptions has a special subclass, the RuntimeException A user defined exception should be a subclass of the exception class

5 Types of exceptions Exceptions which are checked for during compile time are called checked exceptions. Example: SQLException or any userdefined exception extending the Exception class Exceptions which are not checked for during compile time are called unchecked exception. Example: NullPointerException or any class extending the RuntimeException class. All the checked exceptions must be handled in the program. The exceptions raised, if not handled will be handled by the Java Virtual Machine. The Virtual machine will print the stack trace of the exception indicating the stack of exception and the line where it was caused.

6 Types of exceptions ArithmeticException: int a=50/0;//ArithmeticException NullPointerException: String s=null; System.out.println(s.length());//NullPointerException NumberFormatException: String s="abc"; int i=Integer.parseInt(s);//NumberFormatException ArrayIndexOutOfBoundsException: int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException

7 Cntd.. Errors: Error is irrecoverable.
Example: outOfMemoryError,VirtualMachineError etc... Java Exception handling Keywords: Try: try block consist of code that might throw exception and it must be fallowed by either catch or finally block. Syntax try try { //code that may through exception } catch(ExceptionClassName refObj) } Finally { }

8 Cntd.. Java Exception handling Keywords:
Catch: catch block is used to handle the exception witch is thrown by try block We can include multiple catch block. Syntax try { //code that may through exception } catch(ExceptionClassName refObj)

9 Example: Public class test1 { public static void main(String args[])
Int j=20,k=20; int i = 18/0; // may throw exception Sytem.out.println(“excute rest code”+(j+k)): } try { } catch(ArithmeticException e) { Sytem.out.println(e); } Sytem.out.println(“excute rest code”+ (j+k));

10 Cntd.. public class TestMultipleCatchBlock{
  public static void main(String args[]){      try{       int a[]=new int[5];       a[5]=30/0;   }    catch(ArithmeticException e){System.out.println("task1 is completed");}      catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}      catch(Exception e){System.out.println("common task completed");}      System.out.println("rest of the code...");    }   }

11 Handling Exceptions JVM firstly checks whether the exception is handled or not

12 Using multiple catch All catch blocks must be ordered from most specific to most general. Public class test1 { public static void main(String args[]) try { int i = 18/0; // may throw exception int a[]=new int[5]; a[6]=30/0; } catch(ArithmeticException e) { Sytem.out.println(e); } catch(ArrayIndexOutOfBoundsException e) {System.out.println("task2 completed");} Sytem.out.println(“excute rest code”);

13 public class myexception{
public static void main(String args[]){ try{ File f = new File(“myfile”); FileInputStream fis = new FileInputStream(f); } catch(FileNotFoundException ex){ File f = new File(“Available File”); }catch(IOException ex){ //do something here finally{ // the finally block //continue processing here.

14 Nested TRY BLOCK: try { statement 1; statement 2; } catch(Exception e)

15 If a compatible match is found before an exact match, then the compatible match is preferred.
We need to pay special attention on ordering of exceptions in the catch blocks, as it can lead to mismatching of exception and unreachable code. We need to arrange the exceptions from specific to general.

16 Finally Block Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. Java finally block must be followed by try or catch block. class TestFinallyBlock{     public static void main(String args[]){     try{      int data=25/5;      System.out.println(data);  }   catch(NullPointerException e){System.out.println(e);}     finally{System.out.println("finally block is always executed");}     System.out.println("rest of the code...");     }  }

17 Finally Block The Java throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked exception in java by throw keyword. throw new IOException("sorry device error); Throws: Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Syntax for throws return_type method_name() throws exception_class_name{ //method code }

18 Finally Block Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. java finally block must be followed by try or catch block. Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc. For each try block there can be zero or more catch blocks, but only one finally block. try { //code that may through exception } Finally { }

19 Cntd.. class TestFinallyBlock { public static void main(String args[])
{     public static void main(String args[])   Try    int data=25/5;      System.out.println(data); }   catch(NullPointerException e){System.out.println(e);}     Finally { System.out.println("finally block is always executed"); }     System.out.println("rest of the code...");     }  }

20 throw Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. Syntax:throw new IOException("sorry device error); Java Exception propagation An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.

21 throw throws Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception. Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws. Throw is followed by an instance. Throws is followed by class. Throw is used within the method. Throws is used with the method signature. You cannot throw multiple exceptions. You can declare multiple exceptions e.g. public void method()throws IOException,SQLException.

22 Thread A thread can be in one of the five states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: New Runnable Running Non-Runnable (Blocked) Terminated

23 Thread life cycle

24 Thread New :The thread is in new state if you create an instance of Thread class but before the invocation of start() method. Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. Running:The thread is in running state if the thread scheduler has selected it. Non-Runnable (Blocked):This is the state when the thread is still alive, but is currently not eligible to run. Terminated: A thread is in terminated or dead state when its run() method exits.

25 creating threads There are two ways to create a thread:
By extending Thread class By implementing Runnable interface. Thread class: Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface. Commonly used Constructors of Thread class: Thread() Thread(String name) Thread(Runnable r) Thread(Runnable r,String name)

26 creating threads Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). public void run(): is used to perform action for a thread.

27 Methods of thread class
public void run(): is used to perform action for a thread. Each thread starts in a separate call stack. public void start(): starts the execution of the thread.JVM calls the run() method on the thread. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. public void join(): waits for a thread to die. public int getPriority(): returns the priority of the thread. public int setPriority(int priority): changes the priority of the thread. public String getName(): returns the name of the thread. public void setName(String name): changes the name of the thread.

28 Cntd.. public Thread currentThread(): returns the reference of currently executing thread. public int getId(): returns the id of the thread. public Thread.State getState(): returns the state of the thread. public boolean isAlive(): tests if the thread is alive. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. public void suspend(): is used to suspend the thread(depricated). public void resume(): is used to resume the suspended thread(depricated). public void stop(): is used to stop the thread(depricated).

29 Thread class sleep() method
The sleep() method of Thread class is used to sleep a thread for the specified amount of time. Syntax : two methods for sleeping a thread: public static void sleep(long miliseconds)throws InterruptedException public static void sleep(long miliseconds, int nanos)throws InterruptedException

30 Cntd.. class TestSleepMethod1 extends Thread{ public void run(){
  for(int i=1;i<5;i++){       try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}       System.out.println(i);  } }  public static void main(String args[]){     TestSleepMethod1 t1=new TestSleepMethod1();     TestSleepMethod1 t2=new TestSleepMethod1();     t1.start();     t2.start();    }  }

31 Cntd.. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception. class Test1 extends Thread{    public void run(){     for(int i=1;i<5;i++){       System.out.println(i);       } }  public static void main(String args[]){     Test1 t1=new Test1();     t1.start();    }  }

32 Join() method. The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. Syntax: public void join()throws InterruptedException public void join(long milliseconds)throws InterruptedException

33 Join() method. class Test1 extends Thread{ public void run(){
  for(int i=1;i<5;i++){       System.out.println(i);     }  }  public static void main(String args[]){     Test1 t1=new Test1();     Test1 t2=new Test1();      try{ t1.join(); } catch(Exception e){System.out.println(e);} t2.start();  }  }

34 Thread priority Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority. 3 constants defined in Thread class: public static int MIN_PRIORITY public static int NORM_PRIORITY public static int MAX_PRIORITY Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10. Example: m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY);

35 Thread synchronization
Declaring method with synchronized keyword which is used to lock an object for shared resources When thread invoke a synchronized method it automatically acquires lock for that object and releases it when thread completes its task. Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method. (eg 50 lines of code) Syntax to use synchronized block synchronized (object reference expression) { //code block }

36 class Table{    void printTable(int n){      synchronized(this){//synchronized block        for(int i=1;i<=5;i++){         System.out.println(n*i);         try{          Thread.sleep(400);         }catch(Exception e){System.out.println(e);}        }      }    }//end of the method   }   class MyThread1 extends Thread{   Table t;   MyThread1(Table t){   this.t=t;   public void run(){   t.printTable(5);   class MyThread2 extends Thread{   MyThread2(Table t){   t.printTable(100);   public class TestSynchronizedBlock1{   public static void main(String args[]){   Table obj = new Table(); MyThread1 t1=new MyThread1(obj);   MyThread2 t2=new MyThread2(obj);   t1.start();   t2.start();  

37 Thread Deadlock Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

38 public class TestDeadlockExample1 {  
public static void main(String[] args) {    final String resource1 = "ratan jaiswal";   final String resource2 = "vimal jaiswal";       // t1 tries to lock resource1 then resource2       Thread t1 = new Thread() {         public void run() {             synchronized (resource1) {    System.out.println("Thread 1: locked resource 1");   try { Thread.sleep(100);} catch (Exception e) {}       synchronized (resource2) {   System.out.println("Thread 1: locked resource 2");              }            }         }       };   t1.start(); }

39 Inter process communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is implemented by following methods of Object class: Wait() Notify() notifyAll()

40 Inter process communication
Wait(): Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object. public final void wait()throws InterruptedException waits until object is notified. public final void wait(long timeout)throws InterruptedException Notify(): Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened public final void notify() NotifyAll(): Wakes up all threads that are waiting on this object public final void notifyAll()

41 Inter process communication
wait() sleep() wait() method releases the lock sleep() method doesn't release the lock. is the method of Object class is the method of Thread class is the non-static method is the static method should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed. For more detail contact us


Download ppt "Exception Handling Visit for more Learning Resources."

Similar presentations


Ads by Google