Java exception handling - catching superclass exception

耗尽温柔 提交于 2019-12-05 21:01:58

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

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.

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

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.

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