Java异常处理 - 捕获超类异常 [英] Java exception handling - catching superclass exception

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

问题描述

我在Web应用程序中处理异常有一个问题。通常我听到超级类的异常异常是一个坏主意。



我经常写代码来捕获struts action / java servlet类中的所有异常。

  try {
// call business facade
//业务门面调用DAO
/ /从DAO的任何异常气泡
} catch(异常e){
log.error(error,e);
}

如果我们没有抓到超类Exception。我们如何处理任何意外的运行时错误并正确记录。

解决方案

您可以为您的项目处理未捕获的例外。例如,这是我在我的一个项目中的一段代码:

  private static void setDefaultUncaughtExceptionHandler(){
try {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){

@Override
public void uncaughtException(Thread t,Throwable e){
logger .error(线程{}中检测到未捕获的异常,t,e);
}
});
} catch(SecurityException e){
logger.error(无法设置默认未捕获异常处理程序,e);
}
}


I have a question on handling exception in web application. Often I hear catching the super class Exception is a bad idea.

Often I write codes to catch all exceptions in struts action / java servlet classes.

try {
     // call business facade
     // business facade calls DAO
     // any exception from DAO bubbles up 
} catch (Exception e) {
  log.error("error", e);
}

If we do not catch superclass Exception. How do we handle any unexpected runtime errors and logged them appropriately

解决方案

You can setup a DefaultUncaughtExceptionHandler for your project to deal with uncaught exceptions. For example, this is a piece of code that I have in one of my projects:

private static void setDefaultUncaughtExceptionHandler() {
    try {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                logger.error("Uncaught Exception detected in thread {}", t, e);
            }
        });
    } catch (SecurityException e) {
        logger.error("Could not set the Default Uncaught Exception Handler", e);
    }
}

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

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