EXCEPTION HANDLING 1RAJESHREE KHANDE
Errors  Errors do occur in programming.  Problems opening a file, dividing by zero, accessing an out-of-bounds array element, hardware errors, and many more  The question becomes: What do we do when an error occurs?  How is the error handled?  Who handles it?  Should the program terminate?  Can the program recover from the error?  Java uses exceptions to provide the error-handling 2 RAJESHREE KHANDE
Exceptions 3  Exceptions is condition that is caused by run-time error in program  An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.  Represented as an object in Java  Throwing an exception  An error occurs within a method. An exception object is created and handed off to the runtime system. The runtime system must find the code to handle the error.  Catching an exception  The system searches for code to handle the thrown exception. It can be in the same method or in some method in the call stack.RAJESHREE KHANDE
Types of Exception 4 RAJESHREE KHANDE
Checked Exceptions  These are the exceptions which occur during the compile time of the program.  The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not.  These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer.  These exceptions extend the java.lang.Exception class These exceptional conditions should be anticipated and recovered by an application. 5 RAJESHREE KHANDE
Checked Exceptions  Furthermore Checked exceptions are required to be caught. Remember that all the exceptions are checked exceptions unless and until those indicated by Error, RuntimeException or their subclasses.  For example if you call the readLine() method on a BufferedReader object then the IOException may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. Then it passes the name to the constructor for java.io.FileReader and opens the file. However if you do not provide the name of any existing file then the constructor throws java.io.FileNotFoundException which abrupt the application to succeed. Hence this exception will be caught by a well- written application and will also prompt to correct the file name. 6 RAJESHREE KHANDE
Checked Exceptions :Examples  NoSuchFieldException InstantiationException  IllegalAccessException  ClassNotFoundException  NoSuchMethodException  CloneNotSupportedException  InterruptedException 7 RAJESHREE KHANDE
Unchecked Exceptions  Unchecked exceptions are the exceptions which occur during the runtime of the program.  Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class.  These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API.  These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc. 8 RAJESHREE KHANDE
Unchecked Exceptions :Examples  IndexOutOfBoundsException ArrayIndexOutOfBoundsE xception  ClassCastException  ArithmeticException  NullPointerException  IllegalStateException  SecurityException 9 RAJESHREE KHANDE
Error  The errors in java are external to the application.  These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered.  Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement.  Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.IOError would be thrown.  This error will cause the program to terminate but if an application wants then the error might be caught.  An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.  Hence we can say that Errors and runtime exceptions are together called as unchecked exceptions. 10 RAJESHREE KHANDE
Handling Exceptions  Three statements help define how exceptions are handled:  try identifies a block of statements within which an exception might be thrown.  catch - must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. - The statements are executed if an exception of a particular 11 RAJESHREE KHANDE
Handling Exceptions  finally – - must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block. - Even if the try and catch block have a return statement in them, finally will still run. 12 RAJESHREE KHANDE
Handling Exceptions try Block catch Block Exception object creator Exception handler Stmt. that cause an exception Stmt. that handles the exception Throws Exception Object 13 RAJESHREE KHANDE
Handling Exceptions  General form: try { statement(s); } catch (ExceptionType name) { statement(s); } finally { statement(s); } 14 RAJESHREE KHANDE
Exception Class Hierarchy  Java has a predefined set of exceptions and errors that can occur during execution. Exception (derived from Throwable) ClassNotFoundException ArithmeticException IndexOutOfBoundsException NullPointerException IOExceptionRunTimeException This is just a small part of the Exception hierarchy NumberFormatException 15 RAJESHREE KHANDE
Common Java Exception Exception Type Cause of Exception ArithmaticException Caused by math errors such as division by Zero ArrayIndexOutOfBoundException Caused by bad array indexes ArrayStoreException Caused when a program tries to store the wrong type of data in array FileNotFoundException Attempt to access a nonexistent file IOException Caused by general IO failure such as inability to read a file NullPointerException Caused by referencing a Null Object NumberFormatException Caused when conversion between string and number fails 16 RAJESHREE KHANDE
Common Java Exception Exception Type Cause of Exception OUtOfMemoryException Caused by when there is no enough memory to allocate a new object SecurityException Caused when applet tries to perform an action not allowed by the Brower's security setting StackOverFlowException Caused when the system runs out of Stack space StringIndexOutOfBOundException Caused when program attempt to access a nonexistent position in string 17 RAJESHREE KHANDE
 Program did not stop at the point of Exceptional condition  It catches the error condition, print the error messages and then continue the execution 18 RAJESHREE KHANDE
Multiple catch Statement  It is possible to have more than one catch statement in catch block.  Works similar to switch statement  Java does not require any processing at all  We can simpliy have an empty block to avoid program abortion. catch (Exception e);  catch an exception and ignore it. 19 RAJESHREE KHANDE
------- ------ try { ----- } catch (Exception-Type 1) { ------ } catch (Exception-Type 2) { ----- } . . . catch (Exception-Type n) { -------- } 20 RAJESHREE KHANDE
 It is also possible to throw an exception using throw statement  Synatax Example : throw new ArithmaticException(); throw new NumberFormatException 1 All exception object is created by using new operator or simply parameter to catch block throw new throwable_subclass; The throw Keyword 21 RAJESHREE KHANDE
The throw Keyword  For throwing an exception we have to do 1. create an instance an object which is subclass of java.lang.Throwable 2. Use throw keyword to throw an exception Example: throw new IOException(“file not found”); - After throw stmt. The nearest enclosing try block is checked to see it has the catch block that matches the type of exception. - If match is found control is transfer to that catch block. - If not matches with anyone of the specified catch clause the default exception handler halts the program and print he stack trace. 22 RAJESHREE KHANDE
Difference between throw and throws keywords  Whenever we want to force an exception then we use throw keyword.  The throw keyword is used to force an exception.  Moreover throw keyword can also be used to pass a custom message to the exception handling module i.e. the message which we want to be printed. For example throw new MyException ("can't be divided by zero"); 23 RAJESHREE KHANDE
throws  Whereas when we know that a particular exception may be thrown or to pass a possible exception then we use throws keyword.  The Java compiler very well knows about the exceptions thrown by some methods so it insists us to handle them  We can also use throws clause on the surrounding method instead of try and catch exception handler. For Example. static int divide(int first,int second) throws MyException{ 24 RAJESHREE KHANDE
Creating our own Exceptions  Two reasons for defining our own Exception 1 If you want to add additional information if standard exception occur. 2 You may have error condition that arise in your code  To create your own Exception define a subclass of Exception, Which is subclass of Throwable.  All method define by throwable class can be available in that subclass so we may override this methods. 25 RAJESHREE KHANDE
Creating our own Exceptions  Some of methods defined by Class throwable  Example Sr. No Method Description 1 getMessage() Returns a Description of the Exception 2 getStackTrace() Returns an array that contain the stack 3 printStackTrace() Display the stack trace 4 toString Returns a string object containing a description of the exception 26 RAJESHREE KHANDE

Java Exceptions

  • 1.
  • 2.
    Errors  Errors dooccur in programming.  Problems opening a file, dividing by zero, accessing an out-of-bounds array element, hardware errors, and many more  The question becomes: What do we do when an error occurs?  How is the error handled?  Who handles it?  Should the program terminate?  Can the program recover from the error?  Java uses exceptions to provide the error-handling 2 RAJESHREE KHANDE
  • 3.
    Exceptions 3  Exceptions iscondition that is caused by run-time error in program  An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.  Represented as an object in Java  Throwing an exception  An error occurs within a method. An exception object is created and handed off to the runtime system. The runtime system must find the code to handle the error.  Catching an exception  The system searches for code to handle the thrown exception. It can be in the same method or in some method in the call stack.RAJESHREE KHANDE
  • 4.
  • 5.
    Checked Exceptions  Theseare the exceptions which occur during the compile time of the program.  The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not.  These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer.  These exceptions extend the java.lang.Exception class These exceptional conditions should be anticipated and recovered by an application. 5 RAJESHREE KHANDE
  • 6.
    Checked Exceptions  FurthermoreChecked exceptions are required to be caught. Remember that all the exceptions are checked exceptions unless and until those indicated by Error, RuntimeException or their subclasses.  For example if you call the readLine() method on a BufferedReader object then the IOException may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. Then it passes the name to the constructor for java.io.FileReader and opens the file. However if you do not provide the name of any existing file then the constructor throws java.io.FileNotFoundException which abrupt the application to succeed. Hence this exception will be caught by a well- written application and will also prompt to correct the file name. 6 RAJESHREE KHANDE
  • 7.
    Checked Exceptions :Examples NoSuchFieldException InstantiationException  IllegalAccessException  ClassNotFoundException  NoSuchMethodException  CloneNotSupportedException  InterruptedException 7 RAJESHREE KHANDE
  • 8.
    Unchecked Exceptions  Uncheckedexceptions are the exceptions which occur during the runtime of the program.  Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class.  These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API.  These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc. 8 RAJESHREE KHANDE
  • 9.
    Unchecked Exceptions :Examples IndexOutOfBoundsException ArrayIndexOutOfBoundsE xception  ClassCastException  ArithmeticException  NullPointerException  IllegalStateException  SecurityException 9 RAJESHREE KHANDE
  • 10.
    Error  The errorsin java are external to the application.  These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered.  Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement.  Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.IOError would be thrown.  This error will cause the program to terminate but if an application wants then the error might be caught.  An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.  Hence we can say that Errors and runtime exceptions are together called as unchecked exceptions. 10 RAJESHREE KHANDE
  • 11.
    Handling Exceptions  Threestatements help define how exceptions are handled:  try identifies a block of statements within which an exception might be thrown.  catch - must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. - The statements are executed if an exception of a particular 11 RAJESHREE KHANDE
  • 12.
    Handling Exceptions  finally– - must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block. - Even if the try and catch block have a return statement in them, finally will still run. 12 RAJESHREE KHANDE
  • 13.
    Handling Exceptions try Block catchBlock Exception object creator Exception handler Stmt. that cause an exception Stmt. that handles the exception Throws Exception Object 13 RAJESHREE KHANDE
  • 14.
    Handling Exceptions  Generalform: try { statement(s); } catch (ExceptionType name) { statement(s); } finally { statement(s); } 14 RAJESHREE KHANDE
  • 15.
    Exception Class Hierarchy Java has a predefined set of exceptions and errors that can occur during execution. Exception (derived from Throwable) ClassNotFoundException ArithmeticException IndexOutOfBoundsException NullPointerException IOExceptionRunTimeException This is just a small part of the Exception hierarchy NumberFormatException 15 RAJESHREE KHANDE
  • 16.
    Common Java Exception ExceptionType Cause of Exception ArithmaticException Caused by math errors such as division by Zero ArrayIndexOutOfBoundException Caused by bad array indexes ArrayStoreException Caused when a program tries to store the wrong type of data in array FileNotFoundException Attempt to access a nonexistent file IOException Caused by general IO failure such as inability to read a file NullPointerException Caused by referencing a Null Object NumberFormatException Caused when conversion between string and number fails 16 RAJESHREE KHANDE
  • 17.
    Common Java Exception ExceptionType Cause of Exception OUtOfMemoryException Caused by when there is no enough memory to allocate a new object SecurityException Caused when applet tries to perform an action not allowed by the Brower's security setting StackOverFlowException Caused when the system runs out of Stack space StringIndexOutOfBOundException Caused when program attempt to access a nonexistent position in string 17 RAJESHREE KHANDE
  • 18.
     Program didnot stop at the point of Exceptional condition  It catches the error condition, print the error messages and then continue the execution 18 RAJESHREE KHANDE
  • 19.
    Multiple catch Statement It is possible to have more than one catch statement in catch block.  Works similar to switch statement  Java does not require any processing at all  We can simpliy have an empty block to avoid program abortion. catch (Exception e);  catch an exception and ignore it. 19 RAJESHREE KHANDE
  • 20.
    ------- ------ try { ----- } catch (Exception-Type 1) { ------ } catch(Exception-Type 2) { ----- } . . . catch (Exception-Type n) { -------- } 20 RAJESHREE KHANDE
  • 21.
     It isalso possible to throw an exception using throw statement  Synatax Example : throw new ArithmaticException(); throw new NumberFormatException 1 All exception object is created by using new operator or simply parameter to catch block throw new throwable_subclass; The throw Keyword 21 RAJESHREE KHANDE
  • 22.
    The throw Keyword For throwing an exception we have to do 1. create an instance an object which is subclass of java.lang.Throwable 2. Use throw keyword to throw an exception Example: throw new IOException(“file not found”); - After throw stmt. The nearest enclosing try block is checked to see it has the catch block that matches the type of exception. - If match is found control is transfer to that catch block. - If not matches with anyone of the specified catch clause the default exception handler halts the program and print he stack trace. 22 RAJESHREE KHANDE
  • 23.
    Difference between throwand throws keywords  Whenever we want to force an exception then we use throw keyword.  The throw keyword is used to force an exception.  Moreover throw keyword can also be used to pass a custom message to the exception handling module i.e. the message which we want to be printed. For example throw new MyException ("can't be divided by zero"); 23 RAJESHREE KHANDE
  • 24.
    throws  Whereas whenwe know that a particular exception may be thrown or to pass a possible exception then we use throws keyword.  The Java compiler very well knows about the exceptions thrown by some methods so it insists us to handle them  We can also use throws clause on the surrounding method instead of try and catch exception handler. For Example. static int divide(int first,int second) throws MyException{ 24 RAJESHREE KHANDE
  • 25.
    Creating our ownExceptions  Two reasons for defining our own Exception 1 If you want to add additional information if standard exception occur. 2 You may have error condition that arise in your code  To create your own Exception define a subclass of Exception, Which is subclass of Throwable.  All method define by throwable class can be available in that subclass so we may override this methods. 25 RAJESHREE KHANDE
  • 26.
    Creating our ownExceptions  Some of methods defined by Class throwable  Example Sr. No Method Description 1 getMessage() Returns a Description of the Exception 2 getStackTrace() Returns an array that contain the stack 3 printStackTrace() Display the stack trace 4 toString Returns a string object containing a description of the exception 26 RAJESHREE KHANDE