Java – How to do Python's Try Except Else

Question:

How do I do a try except else in Java like I would in Python?

Example:

try:
   something()
except SomethingException,err:
   print 'error'
else:
   print 'succeeded'

I see try and catch mentioned but nothing else.

Asked By: Greg

||

Answers:

While there is no built-in way to do that exact thing. You can do something similar to achieve similar results. The comments explain why this isn’t the exact same thing.

If the execution of the somethingThatCouldError() passes, YAY!! will be printed. If there is an error, SAD will be printed.

try {
    somethingThatCouldError();
    System.out.println("YAY!!");
    // More general, code that needs to be executed in the case of success
} catch (Exception e) {
    System.out.println("SAD");
    // code for the failure case
}

This way is a little less explicit than Python. But it achieves the same effect.

Answered By: jjnguy

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
}
Answered By: Ryan Ische

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.

Answered By: matiascelasco

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.

Answered By: Tezra
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.