在jdk1.5之前,线程不允许抛出异常(各个线程要把自己的checked exception处理掉),但是无法避免的是uncheckedexception,也就是RuntimeException,当抛出异常时子线程会结束,但不会影响主线程。主线程通过try catch是无法捕获子线程异常的,Thread对象提供了setUncaughtExceptionHandler(Thread.UncaughtExceptionHandlereh)方法用来获取线程中产生的异常


import java.lang.Thread.UncaughtExceptionHandler;

public class ThreadTest1 {

public static void main(String[] args) {
MyThread my = new MyThread();
my.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println(t.getName() + " : " + e.getMessage());
// TODO
}
});
try {
my.start();
} catch (Exception e) {
System.out.println("error");
}
}

public static class MyThread extends Thread {
public MyThread() {}
public void run() {
System.out.println("abc");
throw new RuntimeException("just a test");
}
}
}

:下面这种方式无法捕获到线程中抛出的异常。


public static void main(String[] args) {
MyThread my = new MyThread();
try {
my.start();
} catch (Exception e) {
System.out.println("error");
}
}


在jdk1.5以后,引入了callable,该类可以让线程又返回值,同时可以抛出异常。如下:


public class ThreadTest2 {

public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
Callable<String> c1 = new MyThread();
Future<String> future = pool.submit(c1);

try {
System.out.println(future.get());
} catch (Exception e) {
System.out.println("error....");
} finally {
pool.shutdown();
}
}

public static class MyThread implements Callable<String> {
public MyThread() {}

@Override
public String call() throws Exception {
int a = 1/0;
return "abc";
}
}
}