在Java中定义自定义异常处理程序? [英] Define custom exception handler in Java?

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

问题描述

嗯!感谢您找到答案。我接受了重复,因为它是我想要的,它是很好的解释。
感谢大家的答案:)



有没有人有任何建议或一些想法如何在Java中制作一个自定义异常处理程序? / p>

我的意思是修改代码未捕获的标准Java异常处理方法 异常错误更一般地 Throwable



PHP的方式这样做是为了定义一个自定义异常处理程序,但它似乎在Java中没有这样的方式。



我将实现的目标是在Java错误处理过程中插入一个自定义进程:



Uncatched Throwable - >处理我​​的代码外面由JVM - >我的自定义进程 - >恢复JVM标准异常处理如果需要



谢谢所有的想法或建议!



您的答案后编辑



有没有办法生成t他的所有线程的处理程序没有在每个线程中明确声明?
我为此开了一个新问题此处

解决方案

只要记住, Java 多线程异常与他们的线程有关。如果异常未被捕获,您可以使用 thread.setUncaughtExceptionHandler

  thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
@Override
public void uncaughtException t,Throwable e){
System.out.println(catching exception+ e.getMessage());
}
});

或者您可以使用 AOP 定义一个 advice 来处理异常。看看 AspectJ



注意:您需要在此谨慎,因为您可能会最终吞咽异常,并很难弄清错误的来源。 >

Well ! Thanks for having found the answer. I accepted the duplicate since it is exactly what I wanted and it is well explained. Thanks to everybody for your answers :)

Does anyone have advice or some idea on how to make a custom exception handler in Java ?

I mean modifying the standard Java exception handling method for code-uncatched Exceptions, Errors and more generically Throwable.

The PHP way to do this is to define a custom exception handler, but it seems there is no such way in Java.

The goal I would achieve is to insert a custom process in the Java error handling process :

Uncatched Throwable -> handling "outside my code" by the JVM -> my custom process -> resume JVM standard exception handling if wanted

Thanks to all for any idea or suggestion !

Edit after your answers

Is there a way to generify this handler to all threads without declaring explicitly in each thread ? I opened a new question here for this topic.

解决方案

Just mind you, Java is multithreaded, and exception are related to their threads. If the Exception was uncaught you can use thread.setUncaughtExceptionHandler.

 thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("catching exception "+e.getMessage());
        }
    });

Or you can use the AOP approach and define an advice to handle exceptions. Have a look at AspectJ.

Note: You need to be careful here because you might end up swallowing exceptions and having hard time figuring out the source of bugs

这篇关于在Java中定义自定义异常处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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