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