开发者

Java - How to do Python's Try Except Else

开发者 https://www.devze.com 2023-01-11 05:38 出处:网络
How do I do a try except else in Java like I would in Python? Example: try: something() exc开发者_如何学Goept SomethingException,err:

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

Example:

try:
   something()
exc开发者_如何学Goept SomethingException,err:
   print 'error'
else:
   print 'succeeded'

I see try and catch mentioned but nothing 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消