Java多线程捕获异常的处理方式有以下几种:
public class MyRunnable implements Runnable {
@Override
public void run() {
try {
// 执行线程任务
} catch (Exception e) {
// 处理异常
}
}
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<?> future = executorService.submit(new MyRunnable());
try {
future.get();
} catch (Exception e) {
// 处理异常
}
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
// 处理未捕获异常
}
});
public class MyRunnable implements Runnable {
@Override
public void run() {
try {
// 执行线程任务
} catch (Exception e) {
Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);
}
}
}
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
// 处理未捕获异常
}
};
Thread thread = new Thread(new MyRunnable());
thread.setUncaughtExceptionHandler(handler);
thread.start();
无论采用哪种处理方式,都可以根据具体需求来选择适合的处理方式。