views:

113

answers:

3

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  A: 

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.

jjnguy
Close, but what if the code below "YAY" throws an exception? It'd print "YAY" and "SAD".
Adam Crume
@Adam, true. But, you could just put the `Yay` to the bottom of the `try`.
jjnguy
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
@Adam, I see. I will edit my answer.
jjnguy
It seems that this scenario was the reason why C# features `finally` blocks in addition to the standard `try` and `catch`?
Mark LeMoine
@Thants, java Has `finally` too. But that is not what is needed in this question.
jjnguy
A: 

Java doesn't have the equivalent of an "else" clause for Try/Catch. Simply put the content of your "else" clause at the end of your Try block. [Just like in @Justin 'jjnguy' Nelson's answer. :)]

Mike
Actually seems like python's `else` could be equated to `finally`. I'm not a python user but...
Esko
@Esko: No, because `finally` always gets executed whether the code in the `try` block threw an exception or not.
Adam Crume
+4  A: 

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
} finally {
    if (success) {
        // equivalent of Python else goes here
    }
}

EDIT: I don't think the finally is really necessary, since the purpose of the finally block is to execute regardless of any exceptions being thrown in the try block. Since you only want the code to execute on success, you could just have the if statement occur after the try-catch block. Ultimately, it comes down to putting the right code in the try block.

Ryan Ische