Efficient Try/Catch Block Usage in Java

exceptionsjavaprogramming practices

Should catch blocks be used for writing logic i.e. handle flow control etc? Or just for throwing exceptions? Does it effect efficiency or maintainability of code?

What are the side effects (if there are any) of writing logic in catch block?

EDIT:

I have seen a Java SDK class in which they have written logic inside the catch block. For example (snippet taken from java.lang.Integer class):

        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? new Integer(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            String constant = negative ? new String("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }

EDIT2:

I was going through a tutorial where they count it as an advantage of writing logic of exceptional cases inside the exceptions:

Exceptions enable you to write the main flow of your code and to deal
with the exceptional cases elsewhere.

Any specific guidelines when to write logic in catch block and when not to?

Best Answer

The example you cite is due to poor API design (there is no clean way to check whether a String is a valid integer except trying to parse it and catching the exception).

At the technical level, throw and try/catch are control flow constructs that allow you to jump up the call stack, nothing more and nothing less. Jumping the up the call stack implicitly connects code that is not close together in the source, which is bad for maintainability. So it should only be used when you need to do that and the alternatives are even worse. The widely accepted case where the alternatives are worse is error handling (special return codes that need to be checked and passed up each level of the call stack manually).

If you have a case where the alternatives are worse (and you really have considered all of them carefully), then I'd say using throw and try/catch for control flow is fine. Dogma is not a good substitute for judgement.

Related Topic