850 likes | 1.07k Views
Java. Powered By: Arvind Department of Computer science and engineering Radha govind group of institutions,meerut. Exception. The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained .
E N D
Java Powered By: Arvind Department of Computer science and engineering Radha govind group of institutions,meerut
Exception Theexception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained. • What is exception • Dictionary Meaning: Exception is an abnormal condition. • In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Powered By: Arvind
What is exception handling • Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc. Advantage of Exception Handling • The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario: Powered By: Arvind
statement 1; • statement 2; • statement 3; • statement 4; • statement 5;//exception occurs • statement 6; • statement 7; • statement 8; • statement 9; • statement 10; Powered By: Arvind
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the exception will be executed. That is why we use exception handling in java. Powered By: Arvind
An Exception is an abnormal condition in which the normal execution of code gets hampered. double division(double a, double b){ double c=a/b;return c;} If we pass the value of b as zero then answer will be infinite but we can not represent infinite in programming. So JVM will throw an error exception called Arithmetic Exception. With this exception, execution will be halted and execution will get stopped. Powered By: Arvind
Exception occurs in run time during the program execution. They don’t occur at compile time at all. • Keywords: • Try • Catch • Finally • Throw • Throws Powered By: Arvind
Exception Hierarchy • If any other object which does not extend any other class, object is the super most class. • As we know object is the super most class of all the classes declared in the java. throwable is the class which is the super class for all the exceptions. • We have to categories under throwable exception. • Error • Exception Powered By: Arvind
Object throwable Error Exception Runtime Exception Powered By: Arvind
Hierarchy of Exception classes Powered By: Arvind
Types of Exception There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions: • Checked Exception • Unchecked Exception • Error Powered By: Arvind
Difference between checked and unchecked exceptions Checked Exception:The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. Powered By: Arvind
Common scenarios where exceptions may occur 1) Scenario where ArithmeticException occurs.If we divide any number by zero, there occurs an ArithmeticException.int a=50/0; //ArithmeticException • 2) Scenario where NullPointerException occurs.If we have null value in any variable, performing any operation by the variable occurs an NullPointerException. String s=null; System.out.println(s.length());//NullPointerException Powered By: Arvind
3) Scenario where NumberFormatExceptionoccurs: The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.String s="abc"; inti=Integer.parseInt(s);//NumberFormatException 4) Scenario where ArrayIndexOutOfBoundsExceptionoccurs:If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below: int a[]=newint[5]; a[10]=50; //ArrayIndexOutOfBoundsException Powered By: Arvind
Errors • Errors are thrown by the java run time system and indicate some irrecoverable conditions that occur during the program execution. • Once thrown by the system, the application can not recover from it and will come to halt. • Errors need not be handled (Catched) E.g., Java.lang.OutofMemoryError Java.lang.StackOverFlowError Powered By: Arvind
If first method invoke second method, second method invoke first method then both the methods are invoking in cyclic manner. So that this will appear. public class Except { void show(){ System.out.println("hello");display(); }void display(){ System.out.println("Arvind");show(); }public static void main(String[] args) {Except e=new Except();e.show(); }} Powered By: Arvind
Use of try-catch block in Exception handling: Five keywords are used in exception handling: • Try • Catch • Throw • Finally • throws Powered By: Arvind
Exception • Unlike errors, Exceptions can be handled to prevent the program to automatically terminate. • Exceptions can be handled using the try catch block. Powered By: Arvind
try block Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block. Syntax of try with catch block try{ ... }catch(Exception_class_Name reference){} Powered By: Arvind
Syntax of try with finally block:try{ ... }finally{} • catch blockCatch block is used to handle the Exception. It must be used after the try block. Powered By: Arvind
Try, catch and finally • The code which might be throw some exceptions should be kept in try block. • The catch block can have the code to handle the exception or log the same. • Finally block can be used to clean up code or release some resources that are utilized in the program. e.g. finally block released some database resources and file resources. Powered By: Arvind
Syntax: try{// code that might cause an exception is kept here}catch(Exception e){//when an exception occurs, the control comes here}finally{//release some resources here} Powered By: Arvind
Rules • When there is a try block. Catch or finally or both of them block should be there. • There should not be any statement between try, catch and finally. • Finally block is optional. • There can be multiple catch block for a try block. • Catch block is executed only when an exception is thrown. • The narrow exceptions should be declared first and the broader exception last. Powered By: Arvind
import java.io.FileNotFoundException;import java.io.FileReader;public class ExceptionDemo{public double division(double a,double b){ double c=0; try{c=a/b;FileReaderfr=new FileReader("Testfile.txt");}catch(ArithmeticException e){ }catch(FileNotFoundExceptionfe){ }catch(Exception e){ }return c;}public static void main(String[] args) {}} Powered By: Arvind
In this program we have use catch(Exception e ) in the last because Exception e is the broader exception. • Exception e is the super class of ArithmeticExceptione and catch(FileNotFoundExceptionfe. • We should not declared Exception e on the top of these two. • Exception e not is used for specifically exception. Powered By: Arvind
Rules • Finally block always runs even when there is no exception occurs. • When an exception is thrown, the rest of the lines of code in try block will not get executed and the control directly goes for catch or finally. Powered By: Arvind
package myclasses;import java.io.FileNotFoundException;import java.io.FileReader;public class ExceptionDemo{public double division(double a,double b){double c=0; try{c=a/b;FileReaderfr=new FileReader("Testfile.txt");System.out.println("This will not execute");}catch(ArithmeticExceptione){ System.out.println(e.getMessage());}catch(FileNotFoundExceptionfe){ System.out.println(fe.getMessage());}catch(Exception e){ }return c;}public static void main(String[] args) {ExceptionDemoed=new ExceptionDemo();ed.division(15, 2); }} Powered By: Arvind
output Testfile.txt (The system cannot find the file specified) Powered By: Arvind
Problem without exception handling: class Simple{ publicstaticvoid main(String args[]){ int data=50/0; System.out.println("rest of the code..."); }} Output: Exception in thread main java.lang.ArithmeticException: / by zero As displayed in the above example, rest of the code is not executed i.e. rest of the code... statement is not printed. Let's see what happens behind the scene: Powered By: Arvind
What happens behind the code int a=50/0; Powered By: Arvind
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks: • Prints out exception description. • Prints the stack trace (Hierarchy of methods where the exception occurred). • Causes the program to terminate. But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed. Powered By: Arvind
Solution by exception handling: class Simple{ publicstaticvoid main(String args[]){ try{ int data=50/0; }catch(ArithmeticException e){System.out.println(e);} System.out.println("rest of the code..."); }} Output:Exception in thread main java.lang.ArithmeticException: / by zero rest of the code… Powered By: Arvind
Multiple catch block: If you have to perform different tasks at the occurrence of different Exceptions, use multiple catch block. class Excep4{ publicstaticvoid main(String args[]){ try{ int a[]=newint[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..."); } } Powered By: Arvind
Output: Task1 completed rest of the code… Powered By: Arvind
Note: At a time only one Exception is occured and at a time only one catch block is executed. All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception . Powered By: Arvind
Nested try block: • try block within a try block is known as nested try block. Why use nested try block?Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Powered By: Arvind
Syntax: try{ statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e) { } }catch(Exception e) {} Powered By: Arvind
finally block The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc. Powered By: Arvind
Note: Before terminating the program, JVM executes finally block(if any). • Note: finally must be followed by try or catch block. Why use finally block? finally block can be used to put "cleanup" code such as closing a file,closing connection etc. Powered By: Arvind
case 1:Program in case exception does not occur class Simple{ publicstaticvoid 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..."); } } Powered By: Arvind
Output: finally block is always executed Rest of the code … Powered By: Arvind
case 2:Program in case exception occured but not handled • class Simple{ publicstaticvoid main(String args[]){ try{ int data=25/0; 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..."); } } Powered By: Arvind
Output: finally block is always executed Exception in thread main java.lang.ArithmeticException:/ by zero Powered By: Arvind
case 3:Program in case exception occurred and handled class Simple{publicstaticvoid main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(ArithmeticException e) { System.out.println(e); }finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } } Powered By: Arvind
Output: Exception in thread main java.lang.ArithmeticException:/ by zerofinally block is always executedrest of the code... Powered By: Arvind
For each try block there can be zero or more catch blocks, but only one finally block • The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort). Powered By: Arvind
Exception Propagation • Method Call Stack Method4() Method3() Method2() Method1() Main Powered By: Arvind
Method main calls method1 and method1 calls method2 and so on. Then the method4 gets executed first then method3 , at last main will be executed. Powered By: Arvind