Java - How to do Python's Try Except Else

22,368

Solution 1

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
}

Solution 2

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.

Solution 3

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.

Solution 4

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.

Share:
22,368
Greg
Author by

Greg

I'm an avid programmer, web developer and electronics enthusiast. Here's my gift to Python hackers. And you can see everything I'm up to here.

Updated on August 15, 2020

Comments

  • Greg
    Greg almost 4 years

    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.

  • Adam Crume
    Adam Crume almost 14 years
    Close, but what if the code below "YAY" throws an exception? It'd print "YAY" and "SAD".
  • jjnguy
    jjnguy almost 14 years
    @Adam, true. But, you could just put the Yay to the bottom of the try.
  • Adam Crume
    Adam Crume almost 14 years
    My point is that the exception handler can get executed even if somethingThatCouldError() does not throw an exception. I don't think that's exactly what Greg wanted.
  • Mark LeMoine
    Mark LeMoine almost 14 years
    It seems that this scenario was the reason why C# features finally blocks in addition to the standard try and catch?
  • jjnguy
    jjnguy almost 14 years
    @Thants, java Has finally too. But that is not what is needed in this question.
  • Erik Kaplun
    Erik Kaplun over 10 years
    This code block IS NOT AT ALL equivalent to a try-except-else: it will also catch Exception from what is the "else" block; try-except-else does not do that, nor does the solution in Ryan's answer. In addition to not being equivalent, this also goes agaist the principle that try-catch should only be around as small a block of code as possible.
  • Erik Kaplun
    Erik Kaplun over 10 years
    In many cases (e.g. small methods), you either re-throw or return from the catch block, so you can just put the else logic after tye try-catch altogether.
  • jjnguy
    jjnguy over 10 years
    @ErikAllik I mentioned that in my answer = "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."
  • Erik Kaplun
    Erik Kaplun over 10 years
    @jjnguy: yeah; I was saying it's NOT AT ALL similar—it's only superficially/seemingly similar; furthermore, it should NEVER be used because it's error prone and makes the code much less obvious.
  • augurar
    augurar almost 10 years
    -1 To duplicate the semantics of the Python try-catch-else construct, you should not use a finally block, as this will be executed even if there is a return or uncaught exception in the try block. Just put the if(success) block after the try-catch.
  • Ryan Ische
    Ryan Ische almost 10 years
    Thanks @augurar - I played around and reread the docs on else and you are indeed correct.
  • Tripp Kinetics
    Tripp Kinetics about 3 years
    This, I think, should be the accepted answer.