I know exception handling is a topic often discussed in the world of Java. I've read a few threads on here and SO as well.
https://stackoverflow.com/questions/2169339/exception-handling-in-a-java-web-application
I find myself identifying with principles such as Do not suppress or ignore exceptions, Do not catch top-level exceptions, and avoid anti-patterns like Log and Throw.
http://today.java.net/article/2006/04/04/exception-handling-antipatterns#throwingException http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2
Question #1, is there a different standard of practice when it comes to web applications? For example, is it a legitimate use case to catch Exception
for logging purposes and then throw it up the stack?
function void xyz() throws Exception {
try {
} catch (Exception e) {
LOG.error("ERROR: " + e);
throw e;
}
}
function void otherFuncA() throws Exception {
xyz();
}
function void otherFuncB() {
try {
xyz();
} catch (Exception e) {
LOG.error("ERROR: " + e);
throw e;
}
}
I am finding it very hard to accept as a practice because it is generating so much unnecessary code (see otherFuncA
and otherFuncB
), affecting the function calls all through the different layers (DAO, Service, Controller, etc.)
Question #2, do I lose information about an error (let's say what caused a NullPointerException
) if I let unexpected, unchecked exceptions float up to the Controller layer and then, and ONLY then, handle it there (catch Exception
and throw stack trace)? As opposed to logging immediately, and re-throwing (seen above).
Of course, I will still check for specific exception types where applicable.
I seem to find the stack trace is often a better indicator of what went wrong vs. which specific field was causing an error... I am really interested in input from more experienced developers and what best practices/reasoning guide your exception handling.
function
is not a keyword in Java, and you don't use it to define methods. (It is in JavaScript but that is unrelated to Java).