Python 官方文档:入门教程 => 点击学习
目录异常处理UncaughtExceptionHandler异常处理 线程未捕获异常 UncaughtException 需要UncaughtZExceptionHandler 来进
线程未捕获异常 UncaughtException 需要UncaughtZExceptionHandler 来进行处理
那么为什么非要用UncaughtZExceptionHandler呢?
public class ChildException implements Runnable{
public static void main(String[] args) {
new Thread(new ChildException()).start();
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
@Override
public void run() {
throw new RuntimeException();
}
}
public class CantCatch implements Runnable {
public static void main(String[] args) throws InterruptedException {
try {
new Thread(new CantCatch(), "thread0").start();
Thread.sleep(300);
new Thread(new CantCatch(), "thread1").start();
Thread.sleep(300);
new Thread(new CantCatch(), "thread2").start();
Thread.sleep(300);
new Thread(new CantCatch(), "thread3").start();
Thread.sleep(300);
} catch (RuntimeException e) {
System.out.println("catch");
}
}
@Override
public void run() {
throw new RuntimeException();
}
}
在run方法中进行try catch可以捕获到异常,但是特别麻烦,因为需要手动地在每个run方法中都进行try catch
自定义UncaughtExceptionHandler
public class MyUncaughtHandler implements Thread.UncaughtExceptionHandler{
private String name;
public MyUncaughtHandler(String name) {
this.name = name;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
Logger logger = Logger.getAnonymousLogger();
logger.log(Level.WARNING, "线程异常" + t.getName(), e);
System.out.println(name + "捕获" + t.getName()+ e);
}
}
使用自定义的类来捕获异常
public class UseOwnExceptionHandler implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtHandler("MyHandler"));
// try {
new Thread(new UseOwnExceptionHandler(), "thread0").start();
Thread.sleep(300);
new Thread(new UseOwnExceptionHandler(), "thread1").start();
Thread.sleep(300);
new Thread(new UseOwnExceptionHandler(), "thread2").start();
Thread.sleep(300);
new Thread(new UseOwnExceptionHandler(), "thread3").start();
Thread.sleep(300);
// } catch (RuntimeException e) {
// System.out.println("catch");
// }
}
@Override
public void run() {
// try {
throw new RuntimeException();
// } catch (RuntimeException e) {
// System.out.println("e");
// }
}
}
到此这篇关于Java异常处理UncaughtExceptionHandler使用实例代码详解的文章就介绍到这了,更多相关Java UncaughtExceptionHandler内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java异常处理UncaughtExceptionHandler使用实例代码详解
本文链接: https://www.lsjlt.com/news/197940.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0