以下实例演示了多线程异常处理方法:
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");
}
}
以上代码运行输出结果为:
Throwing in MyThread Exception in thread "Thread-0" java.lang.RuntimeException at testapp.MyThread.run(Main.java:19) Exiting main

本文通过一个Java多线程程序实例,展示了如何在自定义线程类中抛出异常,并在主线程中捕获该异常。代码示例中定义了一个名为MyThread的线程子类,在run方法内主动抛出RuntimeException异常。
1716

被折叠的 条评论
为什么被折叠?



