Java 未捕获的全局异常处理程序 [英] Java uncaught global exception handler

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

问题描述

我有一个应用程序,需要编写一个自定义的全局未捕获异常处理程序.我已经阅读了所有 stackoverflow 线程,但每个线程都缺少一个清晰而简单的示例,说明如何实现这一点.

I have an application and need to code a custom global uncaught exception handler. I've read all the stackoverflow threads and each one of them is just missing a clear and simple example of how this is to be implemented.

考虑下面这个简单的例子:

Consider this simple following example:

public static void log(String msg) throws Exception {

    String logPath = "/application/logs/java.log";

    Calendar c = new GregorianCalendar();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String now = format.format(c.getTime());

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(logPath, true)));
    out.println(now + "  " + msg);
    out.close();

}

它抛出一个标准异常,它只是一个标准输出.我如何实现自己的异常,通过将错误输出到日志文件中这样简单的方法来覆盖标准异常?显然,实际应用程序要大得多,而且我们正在讨论未捕获的异常,这就是为什么 try/catch 块不是选项.

It throws a standard exception which is just a standard output. How do I implement my own exception which overrides the standard one by something simple as outputing the error into a log file? Obviously the actual application is much larger and we're talking about uncaught exceptions, which is why try/catch blocks is not the option.

更新:如果你能用一个非常清晰的完整例子来回答,因为我发现了很多例子,比如@RamonBoza 提供的例子,但我不知道如何实现它们,这就是这个问题是关于.

UPDATE: If you could please answer with a very clear full example, because I found dozens of examples like the one @RamonBoza provided, yet I have no idea how to implement them, which is what this question is all about.

UPDATE2: 所以我试图测试下面答案中唯一的例子,它显然不起作用.我创建了一个新的类文件MyRunnable"并将代码粘贴到其中:

UPDATE2: So I've tried to test the only example in the answer below, it obviously doesn't work. I've created a new class file "MyRunnable" and pasted the code in it:

package mypackage;

Thread t = new Thread(new MyRunnable());
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

    public void uncaughtException(Thread t, Throwable e) {
       LOGGER.error(t + " throws exception: " + e);
    }
});
t.start();

//outside that class
class MyRunnable implements Runnable(){
    public void run(){
        throw new RuntimeException("hey you!");
    }
}

不用说,我对此有很多错误.怎么会有课外的东西?

Needless to say I get a bunch of errors with this. How can something be outside of class anyway?

UPDATE3:这是最终有效的解决方案:

UPDATE3: This is the solution that finally works:

package mypackage;

public class MyClass {

    public static void main(String[] args) throws Exception {

        Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { 
            public void uncaughtException(Thread t, Throwable e) { 
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                String stacktrace = sw.toString();
                System.out.println(stacktrace);
            }
        });     

        //main method code

    }

    //Rest of the methods here

}

推荐答案

可以为控制上面代码的线程设置UncaughtExceptionHandler:

You can set UncaughtExceptionHandler for the thread controlling the code above:

// t is the parent code thread
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

    public void uncaughtException(Thread t, Throwable e) {
       LOGGER.error(t + " throws exception: " + e);
    }
 });

UncaughtExceptionHandler 的 Java 文档 -

Java docs for UncaughtExceptionHandler -

当线程由于未捕获的异常而即将终止时Java 虚拟机将查询线程以获取其UncaughtExceptionHandler 使用 Thread.getUncaughtExceptionHandler()并将调用处理程序的 uncaughtException 方法,传递线程和异常作为参数

When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments

setUncaughtExceptionHandler 通常用于释放内存或杀死系统无法杀死的线程,并且可能会保持僵尸状态.

the setUncaughtExceptionHandler is commonly used to free memory or kill threads that the system will not be able to kill, and perhaps, remain zombie.

一个真实的例子:

Thread t = new Thread(new MyRunnable());
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

    public void uncaughtException(Thread t, Throwable e) {
       LOGGER.error(t + " throws exception: " + e);
    }
});
t.start();

//outside that class
class MyRunnable implements Runnable(){
    public void run(){
        throw new RuntimeException("hey you!");
    }
}

这篇关于Java 未捕获的全局异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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