Javaexamples-exception-thread

提供:Dev Guides
移動先:案内検索

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