Java - 如何做 Python 的 Try except Else
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3478222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - How to do Python's Try Except Else
提问by Greg
How do I do a try except else in Java like I would in Python?
我如何像在 Python 中一样在 Java 中尝试除了 else 之外的其他内容?
Example:
例子:
try:
something()
except SomethingException,err:
print 'error'
else:
print 'succeeded'
I see try and catch mentioned but nothing else.
我看到提到尝试和捕捉,但没有别的。
采纳答案by Ryan Ische
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.
我并不完全相信我喜欢它,但这相当于 Python 的 else。它消除了将成功代码放在 try 块的末尾所确定的问题。
bool success = true;
try {
something();
} catch (Exception e) {
success = false;
// other exception handling
}
if (success) {
// equivalent of Python else goes here
}
回答by matiascelasco
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.
当然,在某些情况下,您希望在 try/catch/else 之后放置更多代码,而此解决方案不适合那里,但如果它是您的方法中唯一的 try/catch 块,则它有效。
回答by Tezra
While Ryan's answerof tracking errors with boolean(s) is nice, I think using a "logic block" to "skip forward" is better in this case.
虽然Ryan用布尔值跟踪错误的回答很好,但我认为在这种情况下使用“逻辑块”来“向前跳过”更好。
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>;
在 Java 中,您可以使用创建任意上下文块(范围)<optional-label-name followed by ':'>{...}并为其分配标签。你可以打电话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 finallyis 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.
Try 没有 else 的原因是因为它旨在从特定代码块中捕获特定错误,该代码块要么被处理(通常通过设置默认值或返回),要么冒泡(并且finally仅用于使确保资源不会因为中断而泄漏,即使您爆发了)。在上面的中断示例中,我们通过跳过由于错误而不再相关的代码块来处理异常(向前跳到下一个逻辑步骤)。Ryan 的布尔示例通过记录发生的错误来处理它,并让代码的后面部分在事后对其发生反应。
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.
我认为逻辑块比布尔方法更好(只要你没有基于抛出的错误的复杂逻辑),因为它不需要读者知道整个函数来理解发生了什么。他们看到break <labelname>;并知道程序将有效地向前跳到该块的末尾。布尔值要求程序员跟踪对其做出决定的所有内容。
Obviously, "Skip-forward" and Boolean tracking each have their own advantages, and will usually be more a style choice.
显然,“Skip-forward”和布尔跟踪各有优势,通常更像是一种风格选择。
回答by jjnguy
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, SADwill be printed.
如果执行somethingThatCouldError()通过,YAY!!将被打印。如果有错误,SAD会打印出来。
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.
这种方式不如 Python 明确。但它达到了同样的效果。

