zl程序教程

您现在的位置是:首页 >  后端

当前栏目

捕获其他线程的异常详解编程语言

异常线程编程语言 详解 其他 捕获
2023-06-13 09:20:23 时间

在A线程里起了另B线程,但B线程报错了,这时想要在A线程里捕获B线程的异常是无法做的,除非在捕获B线程前先设置线程捕获器。直接来看代码:

package com.wulinfeng.exceptionHandler; 

import java.lang.Thread.UncaughtExceptionHandler; 

public class ExceptionCatcher { 

 public static void main(String[] args) { 

 // 1、新线程抛异常,main线程无法捕获 

 try { 

 new Thread() { 

 @Override 

 public void run() { 

 System.out.println("第一个空指针来了:"); 

 throw new NullPointerException(); 

 }.start(); 

 } catch (Exception e) { 

 System.out.println("第一次抛出异常!"); 

 // 2、通过线程捕获异常 

 try { 

 // 先休眠,等上面的线程自动结束 

 Thread.sleep(1000); 

 // 先设置捕获线程 

 Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { 

 @Override 

 public void uncaughtException(Thread t, Throwable e) { 

 System.out.printf("线程:%s 抛出异常:%s/n", t.getName(), e.getClass().getName()); 

 e.printStackTrace(); 

 }); 

 // 新起线程抛出异常 

 new Thread() { 

 @Override 

 public void run() { 

 System.out.println("第二个空指针来了:"); 

 throw new NullPointerException(); 

 }.start(); 

 } catch ( 

 Exception e) { 

 System.out.println("第二次抛出异常!"); 

}

运行结果:

第一个空指针来了: 

Exception in thread "Thread-0" java.lang.NullPointerException 

 at com.wulinfeng.exceptionHandler.ExceptionCatcher$1.run(ExceptionCatcher.java:16) 

 at java.lang.Thread.run(Thread.java:745) 

第二个空指针来了: 

线程:Thread-1 抛出异常:java.lang.NullPointerException 

java.lang.NullPointerException 

 at com.wulinfeng.exceptionHandler.ExceptionCatcher$3.run(ExceptionCatcher.java:46) 

 at java.lang.Thread.run(Thread.java:745)

根据线程执行速度不同,新起的线程里exception和本地线程里字符串的打印顺序先后有可能不同。

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/7829.html

cjava