通常程序中我们会对可能出现的异常进行捕获,例如
public static void main(String[] args) {
System.out.println("##### begin");
int dividend = 10;
int divisor = 0;
try {
int result = dividend / divisor;
} catch (Exception e) {
System.out.println(e);
}
System.out.println("##### end");
}
输出结果
##### begin
java.lang.ArithmeticException: / by zero
##### end
如果程序中我们没有对可能出现的异常进行捕获,例如
public static void main(String[] args) {
System.out.println("##### begin");
int dividend = 10;
int divisor = 0;
int result = dividend / divisor;
System.out.println("##### end");
}
输出结果
##### begin
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.yzj.ehr.controller.InnerController.main(InnerController.java:153)
Thread
类有个方法setUncaughtExceptionHandler(UncaughtExceptionHandler eh)
,表示我们可以对一个线程自定义自己的未捕获异常处理器。
我们只需写一个类继承UncaughtExceptionHandler
接口,重写void uncaughtException(Thread t, Throwable e)
方法,然后传入到Thread对象中。
public static void main(String[] args) {
Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("这是对未捕获的异常进行处理方法");
System.out.println("Thread name:" + t.getName() + ",ex:" + e);
}
});
System.out.println("##### begin");
int dividend = 10;
int divisor = 0;
int result = dividend / divisor;
System.out.println("##### end");
}
输出结果
##### begin
这是对未捕获的异常进行处理方法
Thread name:main,ex:java.lang.ArithmeticException: / by zero
对不同线程定义不同的未捕获异常处理器
public static void main(String[] args) {
// 定义main线程的
Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("这是对main线程中未捕获的异常进行处理方法");
System.out.println("@ Thread name:" + t.getName() + ",ex:" + e);
}
});
System.out.println("##### begin");
new Thread(new Runnable() {
@Override
public void run() {
// 定义myThread线程的
Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("这是对myThread线程中未捕获的异常进行处理方法");
System.out.println("# Thread name:" + t.getName() + ",ex:" + e);
}
});
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
// 模拟异常
int[] array = new int[2];
int value = array[2];
}
}, "myThread").start();
int dividend = 10;
int divisor = 0;
int result = dividend / divisor;
System.out.println("##### end");
}
输出结果
##### begin
这是对main线程中未捕获的异常进行处理方法
@ Thread name:main,ex:java.lang.ArithmeticException: / by zero
这是对myThread线程中未捕获的异常进行处理方法
# Thread name:myThread,ex:java.lang.ArrayIndexOutOfBoundsException: 2