Java 处理程序对象如何捕获所有已捕获和未捕获的异常?
How can a Java handler object catch all caught and uncaught exceptions?
我想创建一个中央 Exception
处理程序,它将处理我们整个应用程序抛出的所有异常。未捕获的异常可以通过以下方式处理:
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler());
但是如果条件是这样来的,就不处理了:
try
{
int i = 10/0 ;
}
catch (Exception e)
{
//
}
当我的任何 类 中出现任何异常时,我的中央异常处理程序应该了解它。
在你的 catch 块中:
try
{
int i = 10/0 ;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
编辑:
如果您不想让应用程序崩溃,您可以添加一个 class 静态方法用于记录异常。
public class Logger {
public static void onException(Exception e) {
//Do whatever logging you want to do here.
}
}
然后只需在任何 catch 块中调用 onException 方法即可。
我想创建一个中央 Exception
处理程序,它将处理我们整个应用程序抛出的所有异常。未捕获的异常可以通过以下方式处理:
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler());
但是如果条件是这样来的,就不处理了:
try
{
int i = 10/0 ;
}
catch (Exception e)
{
//
}
当我的任何 类 中出现任何异常时,我的中央异常处理程序应该了解它。
在你的 catch 块中:
try
{
int i = 10/0 ;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
编辑:
如果您不想让应用程序崩溃,您可以添加一个 class 静态方法用于记录异常。
public class Logger {
public static void onException(Exception e) {
//Do whatever logging you want to do here.
}
}
然后只需在任何 catch 块中调用 onException 方法即可。