1 / 41

Exception Handling

Exception Handling. Visit for more Learning Resources. 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.

fmason
Download Presentation

Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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) try { //code that may through exception } 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:

  10. Cntd..

  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.

  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”); FileInputStream fis = new FileInputStream(f); }catch(IOException ex){ //do something here } finally{ // the finally block } //continue processing here. } }

  14. Nested TRY BLOCK: try { statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e) { } } 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.

  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[]) {     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. 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

  22. Thread life cycle

  23. 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.

  24. 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)

  25. 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.

  26. 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.

  27. 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).

  28. 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

  29. Cntd..

  30. 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.

  31. 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

  32. Join() method.

  33. 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);

  34. 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 }

  35. 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.

  36. 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()

  37. 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()

  38. Inter process communication For more detail contact us

More Related