Since every thread runs in it’s own stack in java the main thread will not come to know the status of
Thread started by it. Programmer can implement an interface named UncaughtExceptionHandler to
get a call back from JVM if an Exception occurs in a given thread and its not handled properly.
A simple implementation that demonstrate the use of UncaughtExceptionHandler is given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.ourownjava.corejava.thread; import java.lang.Thread.UncaughtExceptionHandler; /** * * @author ourownjava.com * @date 26th June, 2011 * Example program to demonstrate the use of UncaughtExceptionHandler * */ public class UncaughtExceptionHandlerExample { public static void main(final String args[]){ final Worker worker = new Worker(); worker.setName("worker"); worker.setUncaughtExceptionHandler( new WorkerThreadUncaughtExceptionHandler()); worker.start(); } } class WorkerThreadUncaughtExceptionHandler implements UncaughtExceptionHandler{ public void uncaughtException(final Thread t, final Throwable e) { System.out.println("Exception in "+t.getName()); System.out.println(e.getMessage()); e.printStackTrace(); } } class Worker extends Thread{ public void run(){ System.out.println(100/0); } } |
Console Output.
1 2 3 4 5 |
/opt/mnt/java com.ourownjava.corejava.thread.UncaughtExceptionHandlerExample Exception in worker / by zero java.lang.ArithmeticException: / by zero at com.ourownjava.corejava.thread.Worker.run(UncaughtExceptionHandlerExample.java:35) |
Pingback: How to use UncaughtExceptionHandler in java Thread? | Clean Java