Java 实例 - 多线程异常处理

以下实例演示了多线程异常处理方法:

Main.java 文件

  1. class MyThread extends Thread{
  2. public void run(){
  3. System.out.println("Throwing in " +"MyThread");
  4. throw new RuntimeException();
  5. }
  6. }
  7. class Main {
  8. public static void main(String[] args){
  9. MyThread t = new MyThread();
  10. t.start();
  11. try{
  12. Thread.sleep(1000);
  13. }
  14. catch (Exception x){
  15. System.out.println("Caught it" + x);
  16. }
  17. System.out.println("Exiting main");
  18. }
  19. }

以上代码运行输出结果为:

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