Reputation: 2060
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
Upvotes: 3
Views: 2333
Reputation: 493
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.
Upvotes: 0
Reputation: 139921
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.
Upvotes: 2
Reputation: 66637
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);
}
Upvotes: 1
Reputation: 328598
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);
}
}
Upvotes: 6