如何在 Java 中使用线程异常

问题描述

如何在线程中使用异常?

解决方案

此示例展示了如何在处理线程时处理异常。

class MyThread extends Thread{
   public void run(){
      System.out.println("Throwing in " +"MyThread");
      throw new RuntimeException();
   }
}
public class Main {
   public static void main(String[] args) {
      MyThread t = new MyThread();
      t.start();
      try {
         Thread.sleep(1000);
      } catch (Exception x) {
         System.out.println("Caught it" + x);
      }
      System.out.println("Exiting main");
   }
}

结果

上述代码示例将产生以下结果。

Throwing in MyThread
Exception in thread "Thread-0" java.lang.RuntimeException
        at testapp.MyThread.run(Main.java:19)
Exiting main
java_exceptions.html