Exceptions & its Handling
What’s this Exception It’s an event, which can occur during the execution of a program, & due to which the normal flow of the program's instructions may be disrupted. Class Test { public static void main(String[] args) { System.out.println( 6/0 ); System.out.println( “Hello” ); // do something else } } Exception in thread "main" java.lang.ArithmeticException: / by zero at NewClass.main(NewClass.java:20)
Throwing an Exception When an error occurs within a method, the run-time system creates an object and hands it off to the method. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the relevant method is called throwing an exception. After a method throws an exception, the runtime system attempts to find the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the  call stack
Understanding the Call Stack Exception in thread "main" java.lang.ArithmeticException: / by zero at NewClass.y(NewClass.java:23) at NewClass.x(NewClass.java:21) at NewClass.main(NewClass.java:19) y(),  where exception occured x() main() Class Test { public static void main(String[] args) { x();  } void x() { y();  } void y() { int a = 7/0; } }
Exception Handler The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called.  When an appropriate handler is found, the runtime system passes the exception object to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
Searching for the Exception Handler in the call stack If main forwarded the exception, the thread will abnormally terminate. y(),  where exception occured x() main() throws exception should handle but  may forward exception Looking for appropriate handler Looking for appropriate handler should handle but  may forward exception
Catch or Specify Requirement The code that might throw certain exception must be enclosed either by : A try statement that catches the exception. The try must provide a handler for the exception.  A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception.  Code that fails to honor the Catch or Specify requirement will not compile.  Not all exceptions are subject to the Catch or Specify requirement.
Exception Types : 3 Checked Exception Run-time Exception Error UnChecked Exception
Class Hierarchy java.lang.Object java.lang.Throwable java.lang.Error java.lang.Exception java.lang.RuntimeException
Checked Exception An exceptional condition that a well-written application should anticipate and recover from.  java.io.FileNotFoundException  Java.io.IOException Java.io.InterruptedException Checked exceptions  are subject  to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
Runtime Exception Exceptional conditions that are internal to the application, and that the application usually cannot anticipate.  Usually indicate programming bugs, such as logic errors or improper use of an API.  Runtime exceptions  are not subject  to the Catch or Specify requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.  Ex :-  java.lang.NullPointerException java.lang.ArrayIndexOutOfBoundsException java.lang.ArithmeticException
Error Exceptional conditions that are external to the application, and that the application usually cannot anticipate.  Ex :- java.io.IOError Errors  are not subject  to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.
Runtime Exception due to Logical Errors  public class NewClass  {  public static void main(String[] args) { int array[] = {6,7,8,9,10}; for(int index=0; index<array.length+2; index++) System.out.print(array[index]+” “); System.out.println(&quot;After loop&quot;); } } 6 7 8 9 10 Exception in thread &quot;main&quot;java.lang.ArrayIndexOutOfBoundsException: 5 at NewClass.main(NewClass.java:22)
Runtime Exception due to Logical Errors public class NewClass  {    static Integer i;   public static void main(String[] args) { System.out.println(&quot;1st statement&quot;); System.out.println(i.intValue()); System.out.println(&quot;3rd Statement&quot;); show(&quot;tom&quot;); } static void show(String msg) { System.out.println(msg.toUpperCase()); } } 1st statement Exception in thread &quot;main&quot; java.lang.NullPointerException at NewClass.main(NewClass.java:21)
Runtime Exception due to improper use of API class Test { static Thread t2; public static void main(String[] args) { Thread t1 = new Thread() { public void run() { for(int i=0; i<10; i++) System.out.print(“  new thread  ”); } }; t1.start();  t2.start(); for(int i=0; i<5; i++) System.out.print(“  Main thread  ”); } } Exception in thread &quot;main&quot; java.lang.NullPointerException at NewClass.main(NewClass.java:30) new thread  new thread  new thread  new thread  new thread  new thread  new thread  new thread  new thread  new thread
Runtime Exception due to improper use of API class Test { public static void main(String[] args) { System.out.println(“First statement”); m(“india”); m(35); System.out.println(“Last statement”); } static void m(Object o) { Integer i = (Integer)o; } } First statement Exception in thread &quot;main&quot; java.lang.ClassCastException: java.lang.String   at Test.m(NewClass.java:27)   at Test.main(NewClass.java:21)
Dealing with Exception Using try & catch block of code. public class NewClass  {  public static void main(String[] args) { int array[] = {6,7,8,9,10}; try{ for(int index=0; index<array.length+2; index++) } catch(Exception e) {  System.out.println(“Element with this index doen’t exist”);  } System.out.print(array[index]+” “); System.out.println(&quot;After loop&quot;); } }
  try{   System.out.println(9/0);   System.out.println(&quot;Hello&quot;); } catch(Exception e) {   System.out.println(e.getMessage());   return; }   System.out.println(&quot;Last statement&quot;);
Using finally block try{ System.out.println(9/0); System.out.println(&quot;Hello&quot;); } catch(Exception e) {   System.out.println(e.getMessage());   return; } finally{System.out.println(&quot;2nd Last statement&quot;);} System.out.println(&quot;Last statement&quot;);
java.lang.Object java.lang.Throwable java.lang.Exception java.lang.RuntimeException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException
int arr[] = {5,6,7}; try{ System.out.println(arr[5]); } catch(Exception e) { System.out.println(&quot;first catch&quot;); } catch(RuntimeException re) { System.out.println(&quot;2nd catch&quot;); }
public static void main(String[] args) { System.out.println(m());  } static int m() { try { int x = 7/0; return x; } catch(Exception e) { System.out.println(&quot;catch block&quot;); return 0; } finally { System.out.println(&quot;finally block&quot;); return 1; } }
Handling Checked Exceptions public static void main(String[] args) { m();  } static void m() {   FileInputStream fis = new FileInputStream(&quot;abc.java&quot;); } try{ } catch(FileNotFoundException e) { //….. } throws FileNotFoundException try{ } catch(IOException e) { //….. } throws FileNotFoundException
Creating Custom UnChecked Exceptions public class NewClass  {  public static void main(String[] args) { m();  }  static void m() {  throw new MyException(); } } class MyException extends RuntimeException { MyException() {  super(&quot;This is my exception&quot;);  } } Exception in thread &quot;main&quot; Pack.MyException: This is my exception at NewClass.m(NewClass.java:24) at NewClass.main(NewClass.java:20)
Creating Custom Checked Exceptions public static void main(String[] args) { m();  }  static void m() { throw new MyException(); } class MyException extends RException { MyException() { super(&quot;This is my exception&quot;); } }

Exceptions &amp; Its Handling

  • 1.
  • 2.
    What’s this ExceptionIt’s an event, which can occur during the execution of a program, & due to which the normal flow of the program's instructions may be disrupted. Class Test { public static void main(String[] args) { System.out.println( 6/0 ); System.out.println( “Hello” ); // do something else } } Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero at NewClass.main(NewClass.java:20)
  • 3.
    Throwing an ExceptionWhen an error occurs within a method, the run-time system creates an object and hands it off to the method. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the relevant method is called throwing an exception. After a method throws an exception, the runtime system attempts to find the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack
  • 4.
    Understanding the CallStack Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero at NewClass.y(NewClass.java:23) at NewClass.x(NewClass.java:21) at NewClass.main(NewClass.java:19) y(), where exception occured x() main() Class Test { public static void main(String[] args) { x(); } void x() { y(); } void y() { int a = 7/0; } }
  • 5.
    Exception Handler Theruntime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception object to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
  • 6.
    Searching for theException Handler in the call stack If main forwarded the exception, the thread will abnormally terminate. y(), where exception occured x() main() throws exception should handle but may forward exception Looking for appropriate handler Looking for appropriate handler should handle but may forward exception
  • 7.
    Catch or SpecifyRequirement The code that might throw certain exception must be enclosed either by : A try statement that catches the exception. The try must provide a handler for the exception. A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception. Code that fails to honor the Catch or Specify requirement will not compile. Not all exceptions are subject to the Catch or Specify requirement.
  • 8.
    Exception Types :3 Checked Exception Run-time Exception Error UnChecked Exception
  • 9.
    Class Hierarchy java.lang.Objectjava.lang.Throwable java.lang.Error java.lang.Exception java.lang.RuntimeException
  • 10.
    Checked Exception Anexceptional condition that a well-written application should anticipate and recover from. java.io.FileNotFoundException Java.io.IOException Java.io.InterruptedException Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
  • 11.
    Runtime Exception Exceptionalconditions that are internal to the application, and that the application usually cannot anticipate. Usually indicate programming bugs, such as logic errors or improper use of an API. Runtime exceptions are not subject to the Catch or Specify requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses. Ex :- java.lang.NullPointerException java.lang.ArrayIndexOutOfBoundsException java.lang.ArithmeticException
  • 12.
    Error Exceptional conditionsthat are external to the application, and that the application usually cannot anticipate. Ex :- java.io.IOError Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.
  • 13.
    Runtime Exception dueto Logical Errors public class NewClass { public static void main(String[] args) { int array[] = {6,7,8,9,10}; for(int index=0; index<array.length+2; index++) System.out.print(array[index]+” “); System.out.println(&quot;After loop&quot;); } } 6 7 8 9 10 Exception in thread &quot;main&quot;java.lang.ArrayIndexOutOfBoundsException: 5 at NewClass.main(NewClass.java:22)
  • 14.
    Runtime Exception dueto Logical Errors public class NewClass { static Integer i; public static void main(String[] args) { System.out.println(&quot;1st statement&quot;); System.out.println(i.intValue()); System.out.println(&quot;3rd Statement&quot;); show(&quot;tom&quot;); } static void show(String msg) { System.out.println(msg.toUpperCase()); } } 1st statement Exception in thread &quot;main&quot; java.lang.NullPointerException at NewClass.main(NewClass.java:21)
  • 15.
    Runtime Exception dueto improper use of API class Test { static Thread t2; public static void main(String[] args) { Thread t1 = new Thread() { public void run() { for(int i=0; i<10; i++) System.out.print(“ new thread ”); } }; t1.start(); t2.start(); for(int i=0; i<5; i++) System.out.print(“ Main thread ”); } } Exception in thread &quot;main&quot; java.lang.NullPointerException at NewClass.main(NewClass.java:30) new thread new thread new thread new thread new thread new thread new thread new thread new thread new thread
  • 16.
    Runtime Exception dueto improper use of API class Test { public static void main(String[] args) { System.out.println(“First statement”); m(“india”); m(35); System.out.println(“Last statement”); } static void m(Object o) { Integer i = (Integer)o; } } First statement Exception in thread &quot;main&quot; java.lang.ClassCastException: java.lang.String at Test.m(NewClass.java:27) at Test.main(NewClass.java:21)
  • 17.
    Dealing with ExceptionUsing try & catch block of code. public class NewClass { public static void main(String[] args) { int array[] = {6,7,8,9,10}; try{ for(int index=0; index<array.length+2; index++) } catch(Exception e) { System.out.println(“Element with this index doen’t exist”); } System.out.print(array[index]+” “); System.out.println(&quot;After loop&quot;); } }
  • 18.
    try{ System.out.println(9/0); System.out.println(&quot;Hello&quot;); } catch(Exception e) { System.out.println(e.getMessage()); return; } System.out.println(&quot;Last statement&quot;);
  • 19.
    Using finally blocktry{ System.out.println(9/0); System.out.println(&quot;Hello&quot;); } catch(Exception e) { System.out.println(e.getMessage()); return; } finally{System.out.println(&quot;2nd Last statement&quot;);} System.out.println(&quot;Last statement&quot;);
  • 20.
    java.lang.Object java.lang.Throwable java.lang.Exceptionjava.lang.RuntimeException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException
  • 21.
    int arr[] ={5,6,7}; try{ System.out.println(arr[5]); } catch(Exception e) { System.out.println(&quot;first catch&quot;); } catch(RuntimeException re) { System.out.println(&quot;2nd catch&quot;); }
  • 22.
    public static voidmain(String[] args) { System.out.println(m()); } static int m() { try { int x = 7/0; return x; } catch(Exception e) { System.out.println(&quot;catch block&quot;); return 0; } finally { System.out.println(&quot;finally block&quot;); return 1; } }
  • 23.
    Handling Checked Exceptionspublic static void main(String[] args) { m(); } static void m() { FileInputStream fis = new FileInputStream(&quot;abc.java&quot;); } try{ } catch(FileNotFoundException e) { //….. } throws FileNotFoundException try{ } catch(IOException e) { //….. } throws FileNotFoundException
  • 24.
    Creating Custom UnCheckedExceptions public class NewClass { public static void main(String[] args) { m(); } static void m() { throw new MyException(); } } class MyException extends RuntimeException { MyException() { super(&quot;This is my exception&quot;); } } Exception in thread &quot;main&quot; Pack.MyException: This is my exception at NewClass.m(NewClass.java:24) at NewClass.main(NewClass.java:20)
  • 25.
    Creating Custom CheckedExceptions public static void main(String[] args) { m(); } static void m() { throw new MyException(); } class MyException extends RException { MyException() { super(&quot;This is my exception&quot;); } }