KEMBAR78
Exception Handling | PPT
IADCS Diploma Course Exception Handling U Nyein Oo COO/Director(IT) Myanma Computer Co., Ltd
Introduction to Exception  Is a special type of error   It occurs at runtime in a code sequence   Abnormal conditions that occur while executing the program cause exceptions   If these conditions are not dealt with, then the execution can be terminated abruptly
Purpose of Exception handling Minimize the chances of a system crash, or abrupt program termination For example,  In an I/O operation in a file. If the data type conversion is not properly done, an exception occurs, and the program aborts, without closing the file. This may damage the file, and the resources allocated to the file may not return to the system
Handling Exceptions  When an exception occurs, an object that represents that exception is created  This object is then passed to the method where the exception has occurred The object contains detailed information about the exception. This information can be retrieved and processed  The ’throwable’ class that Java provides is the superclass of the Exception class, which is, in turn, the superclass of individual exceptions
Structure of Exception Object Error Throwable Exception (LinkageError, ThreadDeath, VirtualMachineError) ClassNotFoundException IOException(EOF,FileNotFound) NoSuchFieldException NoSuchMethodException RuntimeException (Arithemetic,IllegalArgument, IndexOutOfBounds,NullPointer)
Structure of Exception(Cont:) Object Throwable Error Exception Runtime Exception uncheck check uncheck
How exception work? //to show exception class UNO{ public static void main(String args[]){ int num=Integer.parseInt(args[0]); System.out.println("Here is "+num); } }
Exception handling Model Is also known as the ‘catch and throw’ model   When an error occurs, an ‘exception’ is thrown, and caught in a block K eywords to handle exceptions try catch throw throws  finally
Structure of the exception handling model  Syntax try { ….  } catch(Exception e1) { …. } catch(Exception e2) { …. } catch(Exception eN) { …. } finally { …. }
Advantages of ‘Catch and Throw’ Model   The programmer has to deal with an error condition only where necessary. It need not be dealt with at every level  An error message can be provided in the exception-handler
‘ try’ and ‘catch’ Blocks   Is used to implement the ‘catch and throw’ model of exception handling A ‘try’ block consists of a set of executable statements   A method, which may throw an exception, can also be included in the ‘try’ block One or more ‘catch’ blocks can follow a ‘try’ block   These ‘catch’ blocks catch exceptions thrown in the ‘try’ block
try’ and ‘catch’ Blocks (Contd…) To catch any type of exception, specify the exception type as ‘Exception’   catch(Exception e) When the type of exception being thrown is not known, the class ‘Exception’  can be used  to catch that exception The error passes through the ‘try catch’ block, until it encounters a ‘catch’ that matches it, or the program terminates
Example of catch and throw model //Number Format Exception Example class Try_Example{ public static void main(String args[]){ try{ int n=Integer.parseInt(args[0]); System.out.println("N is "+n); } catch(Exception e){ System.out.println("E is "+e); } } }
Example(cont) //Arithemetic Exception Example class Try_Example{ public static void main(String args[]){ int demo=0; try{ System.out.println(20/demo); } catch(Exception e){ System.out.println("E is "+e); } } }
Multiple Catch Blocks   Multiple ‘catch()’ blocks process various exception types separately Example try {  doFileProcessing();  displayResults();  }  catch(LookupException e)    {  handleLookupException(e);  }  catch(Exception e)      { System.err.println(“Error:”+e.printStackTrace());  }
Multiple Catch Blocks  (Contd…) When nested ‘try’ blocks are used, the inner ‘try’ block is executed first Any exception thrown in the inner ‘try’ block is caught in the following ‘catch’ blocks If a matching ‘catch’ block is not found, then ‘catch’ blocks of the outer ‘try’ blocks are inspected  Otherwise, the Java Runtime Environment handles the exception
‘finally’ Block Takes care of all the cleanup work when an exception occurs   Can be used in conjunction with a ‘try’ block   Contains statements that either return resources to the system, or print messages Closing a file  Closing a result set (used in Database programming) Closing the connection established with the database
‘ finally’ Block (Contd…) Example try  { doSomethingThatMightThrowAnException( ); }  finally  { cleanup( ); }
‘ finally’ Block (Contd…) Is optional  Is placed after the last ‘catch’ block  The ‘finally’ block is guaranteed to run, whether or not an exception occurs
Example of Finally Block //Finally Block Example class Finally_Example{ public static void main(String args[]){ int demo=0; try{ System.out.println(20/demo); } catch(Exception e){ System.out.println("E is "+e); } finally{ System.out.println("Finally Executed"); } } }
User-defined Exceptions with ‘throw’ and ‘throws’ statements   Exceptions are thrown with the help of the ‘throw’ keyword  The ‘throw’ keyword indicates that an exception has occurred  The operand of throw is an object of a class, which is derived from the class ‘Throwable’  Example of the ‘throw’ statement  try{ if  (flag < 0)   {   throw new MyException( ) ;  // user-defined  } }
User-defined Exceptions with ‘throw’ and ‘throws’ statements (Contd…) A single method may throw more than one exception   Example of the ‘throw’ keyword to handle multiple exceptions   public class Example { public void exceptionExample( ) throws ExException,  LookupException  { try {  // statements  } catch(ExException exmp) { …. } catch(LookupException lkpex) { …. }   }  }
User-defined Exceptions with ‘throw’ and ‘throws’ statements (Contd…) The ‘Exception’ class implements the ‘Throwable’ interface, and provides some useful features for dealing with exceptions   Advantage of subclassing the Exception class is that the new exception type can be caught separately from other Throwable types
User Defined Exception Example public class ExTest{ public static void main(String args[]){ int num=Integer.parseInt(args[0]); try{ if(num<0) throw new MyExceptionTest(); } catch(MyExceptionTest e) { System.out.println(e); } } } public class MyExceptionTest extends ArithmeticException{ MyExceptionTest(){ super(&quot;You have passed Illegal Operation&quot;); } }
Multi catch example public class Pre { public static void main (String argv[]) { try { double d = Double.valueOf(argv[0]).doubleValue();   System.out.println (d); } catch (ArrayIndexOutOfBoundsException e) { System.out.println (&quot;An argument is required.&quot;); return; } catch (NumberFormatException e) { System.out.println (&quot;The argument must be a real number.&quot;); return; } } }
List of Exceptions RuntimeException   ArithmeticException IllegalAccessException   IllegalArgumentException ArrayIndexOutOfBoundsException NullPointerException   SecurityException   ClassNotFoundException   NumberFormatException AWTException IOException FileNotFoundException EOFException   NoSuchMethodException   InterruptedException
Thank You!

Exception Handling

  • 1.
    IADCS Diploma CourseException Handling U Nyein Oo COO/Director(IT) Myanma Computer Co., Ltd
  • 2.
    Introduction to Exception Is a special type of error It occurs at runtime in a code sequence Abnormal conditions that occur while executing the program cause exceptions If these conditions are not dealt with, then the execution can be terminated abruptly
  • 3.
    Purpose of Exceptionhandling Minimize the chances of a system crash, or abrupt program termination For example, In an I/O operation in a file. If the data type conversion is not properly done, an exception occurs, and the program aborts, without closing the file. This may damage the file, and the resources allocated to the file may not return to the system
  • 4.
    Handling Exceptions When an exception occurs, an object that represents that exception is created This object is then passed to the method where the exception has occurred The object contains detailed information about the exception. This information can be retrieved and processed The ’throwable’ class that Java provides is the superclass of the Exception class, which is, in turn, the superclass of individual exceptions
  • 5.
    Structure of ExceptionObject Error Throwable Exception (LinkageError, ThreadDeath, VirtualMachineError) ClassNotFoundException IOException(EOF,FileNotFound) NoSuchFieldException NoSuchMethodException RuntimeException (Arithemetic,IllegalArgument, IndexOutOfBounds,NullPointer)
  • 6.
    Structure of Exception(Cont:)Object Throwable Error Exception Runtime Exception uncheck check uncheck
  • 7.
    How exception work?//to show exception class UNO{ public static void main(String args[]){ int num=Integer.parseInt(args[0]); System.out.println(&quot;Here is &quot;+num); } }
  • 8.
    Exception handling ModelIs also known as the ‘catch and throw’ model When an error occurs, an ‘exception’ is thrown, and caught in a block K eywords to handle exceptions try catch throw throws finally
  • 9.
    Structure of theexception handling model Syntax try { …. } catch(Exception e1) { …. } catch(Exception e2) { …. } catch(Exception eN) { …. } finally { …. }
  • 10.
    Advantages of ‘Catchand Throw’ Model The programmer has to deal with an error condition only where necessary. It need not be dealt with at every level An error message can be provided in the exception-handler
  • 11.
    ‘ try’ and‘catch’ Blocks Is used to implement the ‘catch and throw’ model of exception handling A ‘try’ block consists of a set of executable statements A method, which may throw an exception, can also be included in the ‘try’ block One or more ‘catch’ blocks can follow a ‘try’ block These ‘catch’ blocks catch exceptions thrown in the ‘try’ block
  • 12.
    try’ and ‘catch’Blocks (Contd…) To catch any type of exception, specify the exception type as ‘Exception’ catch(Exception e) When the type of exception being thrown is not known, the class ‘Exception’ can be used to catch that exception The error passes through the ‘try catch’ block, until it encounters a ‘catch’ that matches it, or the program terminates
  • 13.
    Example of catchand throw model //Number Format Exception Example class Try_Example{ public static void main(String args[]){ try{ int n=Integer.parseInt(args[0]); System.out.println(&quot;N is &quot;+n); } catch(Exception e){ System.out.println(&quot;E is &quot;+e); } } }
  • 14.
    Example(cont) //Arithemetic ExceptionExample class Try_Example{ public static void main(String args[]){ int demo=0; try{ System.out.println(20/demo); } catch(Exception e){ System.out.println(&quot;E is &quot;+e); } } }
  • 15.
    Multiple Catch Blocks Multiple ‘catch()’ blocks process various exception types separately Example try { doFileProcessing(); displayResults(); } catch(LookupException e) { handleLookupException(e); } catch(Exception e) { System.err.println(“Error:”+e.printStackTrace()); }
  • 16.
    Multiple Catch Blocks (Contd…) When nested ‘try’ blocks are used, the inner ‘try’ block is executed first Any exception thrown in the inner ‘try’ block is caught in the following ‘catch’ blocks If a matching ‘catch’ block is not found, then ‘catch’ blocks of the outer ‘try’ blocks are inspected Otherwise, the Java Runtime Environment handles the exception
  • 17.
    ‘finally’ Block Takescare of all the cleanup work when an exception occurs Can be used in conjunction with a ‘try’ block Contains statements that either return resources to the system, or print messages Closing a file Closing a result set (used in Database programming) Closing the connection established with the database
  • 18.
    ‘ finally’ Block(Contd…) Example try { doSomethingThatMightThrowAnException( ); } finally { cleanup( ); }
  • 19.
    ‘ finally’ Block(Contd…) Is optional Is placed after the last ‘catch’ block The ‘finally’ block is guaranteed to run, whether or not an exception occurs
  • 20.
    Example of FinallyBlock //Finally Block Example class Finally_Example{ public static void main(String args[]){ int demo=0; try{ System.out.println(20/demo); } catch(Exception e){ System.out.println(&quot;E is &quot;+e); } finally{ System.out.println(&quot;Finally Executed&quot;); } } }
  • 21.
    User-defined Exceptions with‘throw’ and ‘throws’ statements Exceptions are thrown with the help of the ‘throw’ keyword The ‘throw’ keyword indicates that an exception has occurred The operand of throw is an object of a class, which is derived from the class ‘Throwable’ Example of the ‘throw’ statement try{ if (flag < 0) { throw new MyException( ) ; // user-defined } }
  • 22.
    User-defined Exceptions with‘throw’ and ‘throws’ statements (Contd…) A single method may throw more than one exception   Example of the ‘throw’ keyword to handle multiple exceptions public class Example { public void exceptionExample( ) throws ExException, LookupException { try { // statements } catch(ExException exmp) { …. } catch(LookupException lkpex) { …. } } }
  • 23.
    User-defined Exceptions with‘throw’ and ‘throws’ statements (Contd…) The ‘Exception’ class implements the ‘Throwable’ interface, and provides some useful features for dealing with exceptions Advantage of subclassing the Exception class is that the new exception type can be caught separately from other Throwable types
  • 24.
    User Defined ExceptionExample public class ExTest{ public static void main(String args[]){ int num=Integer.parseInt(args[0]); try{ if(num<0) throw new MyExceptionTest(); } catch(MyExceptionTest e) { System.out.println(e); } } } public class MyExceptionTest extends ArithmeticException{ MyExceptionTest(){ super(&quot;You have passed Illegal Operation&quot;); } }
  • 25.
    Multi catch examplepublic class Pre { public static void main (String argv[]) { try { double d = Double.valueOf(argv[0]).doubleValue(); System.out.println (d); } catch (ArrayIndexOutOfBoundsException e) { System.out.println (&quot;An argument is required.&quot;); return; } catch (NumberFormatException e) { System.out.println (&quot;The argument must be a real number.&quot;); return; } } }
  • 26.
    List of ExceptionsRuntimeException ArithmeticException IllegalAccessException IllegalArgumentException ArrayIndexOutOfBoundsException NullPointerException SecurityException ClassNotFoundException NumberFormatException AWTException IOException FileNotFoundException EOFException NoSuchMethodException InterruptedException
  • 27.