面试题答案
一键面试在Java中,捕获线程抛出的异常可以通过以下两种常见方式:
方式一:在run方法内部捕获异常
class MyTask implements Runnable {
@Override
public void run() {
try {
// 可能抛出异常的代码
int result = 10 / 0;
System.out.println("计算结果: " + result);
} catch (ArithmeticException e) {
System.out.println("捕获到异常: " + e.getMessage());
}
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyTask());
thread.start();
}
}
方式二:使用UncaughtExceptionHandler
class MyTask implements Runnable {
@Override
public void run() {
// 可能抛出异常的代码
int result = 10 / 0;
System.out.println("计算结果: " + result);
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyTask());
thread.setUncaughtExceptionHandler((t, e) -> {
System.out.println("线程 " + t.getName() + " 抛出异常: " + e.getMessage());
});
thread.start();
}
}
在第一种方式中,直接在run
方法内使用try-catch
块捕获异常。第二种方式通过设置UncaughtExceptionHandler
来处理线程未捕获的异常,这样可以统一管理线程抛出的异常。