Monday 24 February 2014

Suppressed Exceptions

Exceptions thrown by the try clause suppressed by the exception raised in the finally block.

Example
import java.io.*;

class MyResource{

 void getResource(){
  throw new RuntimeException("I am the RuntimeException");
 }

 public void close(){
  throw new NullPointerException("I am the NullPointer Exception");
 }
}

Class MyResource has two methods, getResource(), which throws RuntimeException , and close(), which throws NullPointerException.

import java.io.*;

class SuppressEx{

 static void callResource()throws Exception{

  MyResource obj = new MyResource();

  try{
   obj.getResource();
  }
  finally{

  }
 }

 public static void main(String args[])throws Exception{
  callResource();
 }
}


Output
Exception in thread "main" java.lang.RuntimeException: I am the RuntimeException
      at MyResource.getResource(MyResource.java:6)
      at SuppressEx.callResource(SuppressEx.java:8)
      at SuppressEx.main(SuppressEx.java:15)

When you tries to run the above program, “ RuntimeException” is thrown. It is as expected. Now will put the close method in the finally block and see the result.
  
import java.io.*;

class SuppressEx{

 static void callResource()throws Exception{

  MyResource obj = new MyResource();

  try{
   obj.getResource();
  }
  finally{
   obj.close();
  }
 }

 public static void main(String args[])throws Exception{
  callResource();
 }
}

Output
Exception in thread "main" java.lang.NullPointerException: I am the NullPointer Exception
   at MyResource.close(MyResource.java:10)
   at SuppressEx.callResource(SuppressEx.java:11)
   at SuppressEx.main(SuppressEx.java:15)

As you observe the output, the exception thrown in the finally clause suppressed the exception thrown in the try clause.




Autocloseable interface                                                 java7 support for suppressed exceptions                                                 Home

No comments:

Post a Comment