Java exception handling - catching superclass exception

醉酒当歌 提交于 2019-12-07 18:16:59

问题


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


回答1:


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);
    }
}



回答2:


In a web application, and in the code snippet you posted, how are you handling the root Exception? It looks like you catch it, log it, and move on.

In 99% of cases in a webapp, it would be better to allow the Exception to bubble up to the configured <error-page> in your web.xml.

It seems unlikely to me that if you catch an unknown error when "calling the business facade" that it's best for your application to keep trucking on with the rest of it's logic.




回答3:


Add multiple catch blocks and leave Exception catch as last one.

try {
     // call business facade
     // business facade calls DAO
     // any exception from DAO bubbles up 
} catch(SuperClassException se)
{
//Do what you want to do when this exception happens.
}catch (Exception e) {
  log.error("error", e);
}



回答4:


Code inside try mostly specifies and flags you about the checked exception which can be caught. Also, looking the codes inside try you can intuit the scenarios for failing case and accordingly unchecked/run-time exception catch block can be added.



来源:https://stackoverflow.com/questions/12409638/java-exception-handling-catching-superclass-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!