Friday, June 19, 2015

Is it possible to catch an uncaught exception that has left the run() method?

Is it possible to catch an uncaught exception that has left the run() method?
Yes, It is possible to catch an uncaught Exception that leaves the run() method by registering an instance that implements an interface UnCaughtExceptionHandler as an Exception Handler.

Whenever any such Uncaught Exception  leaves the run() method, Java Virtual Machine (JVM)
does the following:
  • it calls a special private method, dispatchUncaughtException(), on the Thread class in which the exception occurs;
  • it then terminates the thread in which the exception occurred.

Instance registering of UnCaughtExceptionHandler is done by invoking the static method Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler), which tells the JVM to use the provided handler in case there is no specific handler registerd on the thread itself, or by invoking setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) on the thread instance itself.
package indoscopy;

public class UnCaughtExceptionClass {
  public static void main(String[] args) {

     Thread t = new Thread(new adminThread());
     t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

     public void uncaughtException(Thread t, Throwable e) {
     System.out.println(t + " throws exception: " + e);
     }
     });
     // this will call run() function
     t.start();
     }
  }

  class adminThread implements Runnable {

     public void run() {
     throw new RuntimeException();
     }
  } 

No comments:

Post a Comment