如何在 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.htm
廣告
© . All rights reserved.