我想讨论一件事,当线程中的run方法体中发生异常时,它将在哪里反映(调用者)以及如何处理。
这是我的代码:
class MyThread extends Thread{
public void run() throws IllegalInterruptedException{
Thread.currentThread().sleep(1234);
}
}
那么 who(Caller) 将管理这个异常。
我想讨论一件事,当线程中的run方法体中发生异常时,它将在哪里反映(调用者)以及如何处理。
这是我的代码:
class MyThread extends Thread{
public void run() throws IllegalInterruptedException{
Thread.currentThread().sleep(1234);
}
}
那么 who(Caller) 将管理这个异常。
有两种不同的情况:
示例程序:
public class ThreadGroupDemo extends ThreadGroup {
public ThreadGroupDemo() {
super("This is MyThreadGroupDemo");
}
public void uncaughtException(Thread t, Throwable ex) {
// Handle your exception here ....
}
}
Thread t = new Thread(new ThreadGroupDemo(), "My Thread") {
// Some code here ......
};
t.start();
注意:查看此链接。
还有另一种选择 - 使任务成为 Callable 并使用 Executors 提交它。然后,当您获得 Future 时,您将自动包装任何异常。
当发生不寻常的事情时,程序会抛出异常。此处提供了一般教程,但总结是您的程序将在引发异常的类中搜索,并希望找到处理它的方法:可能是一个 catch 语句,如:
catch (IllegalInterruptedException e) {
//what you want the program to do if an IllegalInterruptedException
//is thrown elsewhere and caught here. For example:
System.err.println( "program interrupted!" + e.getMessage() );
}
如果你的程序在抛出语句的类中找不到 catch 语句,它会在父类中寻找处理它的东西。请注意,无论子类在抛出异常时正在做什么,都会在抛出异常时停止。出于这个原因,您应该将可能引发异常的代码块包含在“try”块中,然后在“finally”语句中执行您想要执行的任何内容,无论如何都会执行。
上面链接的教程真的很有帮助。
如果我理解得很好,您希望能够处理在另一个线程中触发的异常。看一下 setDefaultUncaughtExceptionHandler,一个带有示例的页面:
你可以看到run()
喜欢main()
并得到你自己的答案。但我不认为你可以覆盖run()
和声明new nonRuntime-Exceptions
.. 所以你会得到一个编译错误。
ps:我找不到IllegalInterruptedException
,也许你想说InterruptedException