Java 實(shí)例 - 多線程異常處理

Java 實(shí)例 Java 實(shí)例

以下實(shí)例演示了多線程異常處理方法:

/*
 author by w3cschool.cc
 Main.java
 */

class MyThread extends Thread{
   public void run(){
      System.out.println("Throwing in " +"MyThread");
      throw new RuntimeException();
   }
}
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");
   }
}

以上代碼運(yùn)行輸出結(jié)果為:

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

Java 實(shí)例 Java 實(shí)例