Java 中是否有未处理的异常处理程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/588634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an unhandled exception handler in Java?
提问by Bogdan
If i remember correctly in .NET one can register "global" handlers for unhandled exceptions. I am wondering if there is something similar for Java.
如果我在 .NET 中没记错的话,可以为未处理的异常注册“全局”处理程序。我想知道 Java 是否有类似的东西。
回答by Joachim Sauer
Yes, there's the defaultUncaughtExceptionHandler, but it only triggers if the Threaddoesn't have a uncaughtExceptionHandlerset.
是的,有defaultUncaughtExceptionHandler,但只有在Thread没有uncaughtExceptionHandler集合时才会触发。
回答by Bogdan
回答by alexpopescu
Yes, there is an 'almost' global such handler available in ThreadGroup. It is not as global as the one you are mentioning, but you can basically achieve the same functionality.
是的,在ThreadGroup 中有一个“几乎”全局的此类处理程序。它不像您提到的那样具有全局性,但是您基本上可以实现相同的功能。
Starting with Java 5, there is a similar functionality available directly on the Thread class.
从 Java 5 开始,在Thread 类上直接提供了类似的功能。
回答by jcrossley3
Often, Java frameworks like Struts and Spring (and the Servlet Spec, IIRC) allow you to set a global exception handler. These mechanisms are specific to each framework, though.
通常,像 Struts 和 Spring(以及 Servlet Spec,IIRC)这样的 Java 框架允许您设置全局异常处理程序。但是,这些机制特定于每个框架。
回答by TofuBeer
Assuming it is like catch(...) in C++ you would do:
假设它就像 C++ 中的 catch(...) 你会这样做:
try
{
// your code here
}
catch(Throwable ex)
{
// any sort of exception, even if the VM has choked on a peanut
}
In general this isn't a good idea unless you are dealing with 3rd party code (you should try to always throw subclasses of Exception (and not RuntimeException) in your own code - unless it indicates a programmer error that should be delt with via unit testing.
一般来说,这不是一个好主意,除非您正在处理 3rd 方代码(您应该尝试始终在自己的代码中抛出 Exception 的子类(而不是 RuntimeException) - 除非它表明应该通过单元删除的程序员错误测试。

