java线程异常 [英] java thread exceptions
问题描述
是否可以将异常传播到主方法?
我们正在谈论从 Thread.run
方法抛出的未经检查的异常。
默认情况下,系统错误中会出现这样的情况:
线程Thread-0中的异常java .lang.RuntimeException
在Main $ 1.run(Main.java:11)
在java.lang.Thread.run(Thread.java:619)
这是printStackTrace对未处理异常的结果。要处理它,您可以添加自己的UncaughtExceptionHandler:
线程t = new Thread(new Runnable(){
public void run(){
throw new RuntimeException();
}
});
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
public void uncaughtException(Thread t,Throwable e){
System.out.println(exception+ e + 从线程+ t);
}
});
t.start();
要设置所有线程的处理程序,请使用静态方法 Thread.setDefaultUncaughtExceptionHandler
。
Assume a thread is started from the main method. What happens if an exception is thrown in the thread but not handled within the thread?
Is it possible to propagate the exception back to the main method?
We are talking about unchecked exceptions thrown from Thread.run
method.
By default, you will get sth like this in system error:
Exception in thread "Thread-0" java.lang.RuntimeException
at Main$1.run(Main.java:11)
at java.lang.Thread.run(Thread.java:619)
This is the result of printStackTrace for unhandled exceptions. To handle it, you can add your own UncaughtExceptionHandler:
Thread t = new Thread(new Runnable(){
public void run() {
throw new RuntimeException();
}
});
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("exception " + e + " from thread " + t);
}
});
t.start();
To set handler for all threads use a static method Thread.setDefaultUncaughtExceptionHandler
.
这篇关于java线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!