Exception Handling Visit for more Learning Resources.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Java Thread Programming
Multithreading / Concurrency
Multi Threading.
Java Multithreading.
Multithreading.
MIT AITI 2003 Lecture14 Exceptions
Multithreaded Programming in Java
Introduction to Exceptions in Java
THREADS.
Multithreading in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Advanced Programming Behnam Hatami Fall 2017.
ATS Application Programming: Java Programming
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Exception Handling in Java
Programming with Shared Memory Java Threads and Synchronization
Managing Errors and Exceptions
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Tutorial Exceptions Handling.
Threads and Multithreading
Tutorial MutliThreading.
Java Basics Exception Handling.
Exception Handling.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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

Hierarchy

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

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.

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

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 { }

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)

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

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...");    }   }

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

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”);

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.

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

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.

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...");     }  }

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 }

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 { }

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...");     }  }

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.

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.

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

Thread life cycle

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.

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)

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.

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.

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

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

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();    }  }

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();    }  }

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

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();  }  }

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

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 }

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();  

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.

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(); }

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

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

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