在Java中定义自定义异常处理程序? [英] Define custom exception handler in 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屋!