Java - How to do Python's Try Except Else

I'm not entirely convinced that I like it, but this would be equivalent of Python's else. It eliminates the problem's identified with putting the success code at the end of the try block.

bool success = true;
try {
    something();
} catch (Exception e) {
    success = false;
    // other exception handling
}
if (success) {
    // equivalent of Python else goes here
}

What about this?

try {
    something();
} catch (Exception e) {
    // exception handling
    return;
}
// equivalent of Python else goes here

Sure, there are some cases where you want to put more code after the try/catch/else and this solution don't fit there, but it works if it's the only try/catch block in your method.


While Ryan's answer of tracking errors with boolean(s) is nice, I think using a "logic block" to "skip forward" is better in this case.

In Java, you are allowed to create arbitrary context blocks (scopes) using <optional-label-name followed by ':'>{...} and assign labels to them. You can than call break <labelname>;

Here is an example of what I mean that you can play with:

private static void trycatchelsetest(boolean err) {
    myLogicBlock: {
        try {
            System.out.println("TRY");
            { //unlabeled block for demonstration
            if(err)
                throw new IOException("HELLO!");
            }
        } catch(IOException e) {
            System.out.println("CATCH");
            break myLogicBlock;
        } finally {
            System.out.println("FINALLY");
        }

        System.out.println("ELSE");
    }

    System.out.println("END");
}

The reason Try doesn't have an else is because it is meant to catch a specific error from a specific block of code, which is either handled (usually by setting a default or returning), or bubbled up (and finally is offered only to make sure resources aren't leaked because of the interrupt, even if you break out). In the break example above, we are handling the exception by skipping the block of code that is no longer relevant because of the error (skipping forward to the next logical step). The boolean example by Ryan handles it by noting the error happened, and letting latter parts of the code react to it happening after the fact.

I think the logic block is better than the boolean approach (as long as you have no complex logic based on what errors have been thrown) because it doesn't require the reader to know the entire function to understand what happens. They see break <labelname>; and know that the program will effectively skip forward to the end of that block. The boolean requires the programmer to track down everything that makes decisions on it.

Obviously, "Skip-forward" and Boolean tracking each have their own advantages, and will usually be more a style choice.