I have a question about defense programming and handling of exceptions.
Here is a pseudo-code snippet first:
try {
// do some core logic;
} catch (BadException e) {
ErrorCode ec = e.getErrorCode();
if (ec < 10) {
// handle badException, because its not so bad.
} else {
// do not handle and log
}
}
You see I want to execute some core-logic, that can fail on different conditions and prerequisites. In some of this exceptional cases I want to handle this exception and write some reports and do some other stuff. In all other cases I want to log or rethrow the exception. At my pseudo-code snippet I expressed it with ErrorCodes lower than 10.
Now are in doubt, if this is good coding practice to handle some of that error cases, if I can check for the prerequisites before executing the core-statements.
But if I change the code to check for prerequisites I will end up in code that reads like this here:
try {
// check prerequisites.
if (allIsOk) {
// execute core logic;
} else {
// do handle that cases and write back some reports
}
} catch (BadException e) {
// do not handle and log
}
But I also don't really like this way, because the try-statement with its core-logic is cluttered up with an if-statement. Should I really blow up the try block with handling of some special parts of BadException in addition to the BadException-Catch-Block?