我正在使用Runnable线程,如下所示:
private void startCalculateThread() {
new Thread(new Runnable() {
@Override public void run() {
try {
// calculatingSomething();
} catch (Exception e) {
throw new RuntimeException();
}
}
}).start();
}
然后我在其他方法startCalculateThread
中调用此calculate
方法,如下所示:
private void calculate(final String message){
startCalculateThread();
}
我在RuntimeException
方法中从新线程中抛出startCalculateThread
。我想我可以使用Callable
,但我不想这样做。有人可以告诉如何从线程抛出异常调用方法calculate
。
答案 0 :(得分:2)
我同意@Henry - 你想要分离的程序流程但不是例外。你应该重新思考你想要达到的目标。
这不是你想要的(calculate
中没有处理异常),但可能正是你要找的......
import java.lang.Thread.UncaughtExceptionHandler;
public class ThreadTest implements UncaughtExceptionHandler {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override public void run() {
throw new RuntimeException();
}
});
t.setUncaughtExceptionHandler(new ThreadTest()); // <= check this
t.start();
System.out.println("finished");
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("exception");
}
}
答案 1 :(得分:0)
线程有自己的执行流程
所以你不能“直接”从calculate()
方法中捕获异常
但是,您可以通过对要捕获抛出异常的线程使用Thread.setUncaughtExceptionHandler()
方法来“间接”执行此操作。
抛出异常时,uncaughtException()
事件将传输抛出的异常信息和抛出它的线程。
您可以将实际代码修改为:
private void calculate(final String message){
Thread t = new Thread(new Runnable() {
@Override public void run() {
try {
// calculatingSomething();
} catch (Exception e) {
throw new RuntimeException();
}
}
});
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
// handling the exception
}
});
t.start();
}