52

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.

4 Answers 4

36

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
}
3
  • 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. Jan 11, 2014 at 16:56
  • 6
    -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.
    – augurar
    Jul 7, 2014 at 17:49
  • 3
    Thanks @augurar - I played around and reread the docs on else and you are indeed correct.
    – Ryan Ische
    Jul 8, 2014 at 13:39
10

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.

0
5

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.

1
  • 1
    This, I think, should be the accepted answer. May 13, 2021 at 17:02
3

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.

8
  • 5
    Close, but what if the code below "YAY" throws an exception? It'd print "YAY" and "SAD".
    – Adam Crume
    Aug 13, 2010 at 15:26
  • 1
    @Adam, true. But, you could just put the Yay to the bottom of the try.
    – jjnguy
    Aug 13, 2010 at 15:31
  • 2
    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.
    – Adam Crume
    Aug 13, 2010 at 15:33
  • 16
    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. Jan 11, 2014 at 16:54
  • 5
    @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. Jan 14, 2014 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.