Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling Java

Tags:

java

class chain_exceptions{
   public static void main(String args[]){
      try
      {
         f1();
      }
      catch(IndexOutOfBoundsException e)
      {
         System.out.println("A");
         throw new NullPointerException(); //Line 0
      }
      catch(NullPointerException e) //Line 1
      {
         System.out.println("B");
         return;
      }
      catch (Exception e)
      {
         System.out.println("C");
      }
      finally
      {
         System.out.println("D");
      }
      System.out.println("E");
   }

   static void f1(){
      System.out.println("Start...");
      throw new IndexOutOfBoundsException( "parameter" );
   }
}

I expected the Line 1 to catch the NullPointerException thrown from the Line 0 but it does not happen.

But why so ?.

When there is another catch block defined, why cant the NPE handler at Line1 catch it ?

Is it because the "throw" goes directly to the main() method ?

like image 328
UnderDog Avatar asked Nov 29 '22 02:11

UnderDog


1 Answers

Catch{ . . . } blocks are associated with try{ . . . } blocks. A catch block can catch exceptions that are thrown from a try block only. The other catch blocks after first catch block are not associated with a try block and hence when you throw an exception, they are not caught. Or main() does not catch exceptions.

A kind of this for each catch block will do what you are trying to do.

try{
  try
  {
     f1();
  }
  catch(IndexOutOfBoundsException e)
  {
     System.out.println("A");
     throw new NullPointerException(); //Line 0
  }
}
catch(NullPointerException e) //Line 1
{
     System.out.println("B");
     return;
}
like image 62
sr01853 Avatar answered Dec 19 '22 00:12

sr01853