java线程异常 [英] java thread exceptions

查看:157
本文介绍了java线程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个线程是从main方法启动的。如果线程中抛出异常但在线程中没有处理,会发生什么?



是否可以将异常传播到主方法?

解决方案

我们正在谈论从 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆