线程使用--使用setUncaughtExceptionHandler方法注册Runtime异常的处理者

Java多线程

1、不允许抛出受检异常,所以必须自己处理受检异常。

2、但是RuntimeException不可避免,抛出该异常时子线程会结束,但是主线程不会知道,因为主线程通过try catch无法捕获子线程异常。

代码:

  1. package com.csdn.test.threadmgr;
  2.  
  3. public class TestUncatchException
  4. {
  5. public static class TestRuntimeExceptionThread extends Thread
  6. {
  7. public TestRuntimeExceptionThread()
  8. {
  9. super.setName("thread-TestRuntimeExceptionThread");
  10. }
  11.  
  12. @Override
  13. public void run()
  14. {
  15. throw new RuntimeException("run time exception");
  16. }
  17. }
  18.  
  19. public static void main(String[] args)
  20. {
  21. try
  22. {
  23. Thread test = new TestRuntimeExceptionThread();
  24. // 设置线程默认的异常捕获方法
  25. // test.setUncaughtExceptionHandler((Thread t, Throwable e) -> {System.out.println(t.getName() + ": " + e.getMessage());});
  26. test.start();
  27. }
  28. catch(Exception e)
  29. {
  30. System.out.println("catch thread exception");
  31. }
  32. }
  33.  
  34. }

输出:

Exception in thread "thread-TestRuntimeExceptionThread" java.lang.RuntimeException: run time exception
    at com.csdn.test.threadmgr.TestUncatchException$TestRuntimeExceptionThread.run(TestUncatchException.java:15)

 

解决方案:

Thread对象提供了setUncaughtExceptionHandler方法用来获取线程中产生的异常。而且建议使用该方法为线程设置异常捕获方法。

代码:

  1. package com.csdn.test.threadmgr;
  2.  
  3. public class TestUncatchException
  4. {
  5. public static class TestRuntimeExceptionThread extends Thread
  6. {
  7. // 指定线程名称 便于问题定位
  8. public TestRuntimeExceptionThread()
  9. {
  10. super.setName("thread-TestRuntimeExceptionThread");
  11. }
  12.  
  13. @Override
  14. public void run()
  15. {
  16. throw new RuntimeException("run time exception");
  17. }
  18. }
  19.  
  20. public static void main(String[] args)
  21. {
  22. Thread test = new TestRuntimeExceptionThread();
  23. // 设置线程默认的异常捕获方法
  24. test.setUncaughtExceptionHandler((Thread t, Throwable e) -> {
  25. System.out.println(t.getName() + ": " + e.getMessage());
  26. });
  27. test.start();
  28. }
  29.  
  30. }

输出:

thread-TestRuntimeExceptionThread: run time exception

 

参考博客:

https://blog.csdn.net/u013256816/article/details/50417822

posted @ 2020-11-19 16:24  CharyGao  阅读(56)  评论(0)    收藏  举报