java - 如何从线程中捕获异常

标签 java multithreading

我有Java主类,在类中,我启动了一个新线程,在主类中,它一直等到线程死亡。在某个时刻,我从线程中抛出了运行时异常,但我无法在主类中捕获从线程中抛出的异常。

代码如下:

public class Test extends Thread
{
  public static void main(String[] args) throws InterruptedException
  {
    Test t = new Test();

    try
    {
      t.start();
      t.join();
    }
    catch(RuntimeException e)
    {
      System.out.println("** RuntimeException from main");
    }

    System.out.println("Main stoped");
  }

  @Override
  public void run()
  {
    try
    {
      while(true)
      {
        System.out.println("** Started");

        sleep(2000);

        throw new RuntimeException("exception from thread");
      }
    }
    catch (RuntimeException e)
    {
      System.out.println("** RuntimeException from thread");

      throw e;
    } 
    catch (InterruptedException e)
    {

    }
  }
}

有人知道为什么吗?

最佳答案

使用 Thread.UncaughtExceptionHandler

Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};
Thread t = new Thread() {
    @Override
    public void run() {
        System.out.println("Sleeping ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
        }
        System.out.println("Throwing exception ...");
        throw new RuntimeException();
    }
};
t.setUncaughtExceptionHandler(h);
t.start();

关于java - 如何从线程中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6546193/

相关文章:

java - 有没有办法在 Spring WS 2 中公开静态 XSD?

c# - BlockingCollection 多个消费者

java - volatile 与非 volatile

java - volatile 保证可变对象的安全发布?

python - 在 Shell/终端或变量更改中按键时退出循环

java - Spring Boot @ResponseBody Jackson - 转义所有字符串字段

java - QueryDsl - 带字符串值的 case 表达式

java - Android Id 及其可靠性

java - 如何从 GUI 启动控制台程序?

multithreading - Node JS 是否限制每个打开的 HTTP 连接只有一个线程?