You cannot catch child thread exceptions through try catch. The Thread object provides the setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) method to obtain exceptions generated in the thread.
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 | package threads;
import java.lang.Thread.UncaughtExceptionHandler;
public class TextException
{
public static void main(String[] args)
{
Test test = new Test();
test.setUncaughtExceptionHandler( new UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
System.out.println(t.getName() + " : " + e.getMessage());
}
});
}
public static class Test extends Thread
{
public Test()
{
}
public void run()
{
throw new RuntimeException( "just a test" );
}
}
}
|
Copy after login
For more articles related to Java multi-threaded programming examples of catching sub-thread exceptions, please pay attention to the PHP Chinese website!