Python try-except with of if else
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20652527/
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
Python try-except with of if else
提问by Varghese Chacko
I have the following code:
我有以下代码:
try:
pk = a_method_that_may_raise_an_exception()
except:
method_to_be_executed_in_case_of_exception_or_pk_is_false()
else:
if pk:
process_pk()
else:
method_to_be_executed_in_case_of_exception_or_pk_is_false()
This could be written as:
这可以写成:
try:
if a_method_that_may_raise_an_exception():
process_pk()
else:
method_to_be_executed_in_case_of_exception_or_pk_is_false()
except:
method_to_be_executed_in_case_of_exception_or_pk_is_false()
I am not happy that the method method_to_be_executed_in_case_of_exception_or_pk_is_false()appears twice, i.e in else of both if and try...except.
我不高兴该方法method_to_be_executed_in_case_of_exception_or_pk_is_false()出现两次,即在 if 和 try...except 的 else 中。
Is there a better way to do this?
有一个更好的方法吗?
采纳答案by qwwqwwq
You could try the following:
您可以尝试以下操作:
class PKIsFalseException(Exception):
pass
try:
pk = a_method_that_may_raise_an_exception()
if not pk: raise PKIsFalseException()
except (PKIsFalseException, CatchableExceptions):
method_to_be_executed_in_case_of_exception_or_pk_is_false()
I have updated with specific exception catching instead of catching all exceptions, which is always bad practice as others have pointed out. Assuming that your method will throw one of CatchableExceptions.
我已经更新了特定的异常捕获,而不是捕获所有异常,正如其他人指出的那样,这总是不好的做法。假设您的方法将抛出CatchableExceptions.
回答by mgilson
What about something like:
怎么样:
try:
pk = a_method_that_may_rise_an_exception()
except HandleableErrors:
pk = False
finally:
if pk:
process_pk()
else:
method_to_be_executed_in_case_of_exception_or_pk_is_false()
Really, we don't even need the finallyclause here...
真的,我们甚至不需要finally这里的条款......
try:
pk = a_method_that_may_rise_an_exception()
except HandleableErrors:
pk = False
if pk:
process_pk()
else:
method_to_be_executed_in_case_of_exception_or_pk_is_false()
回答by poke
If you return from the function afterwards, you could do it like this:
如果你之后从函数返回,你可以这样做:
try:
pk = a_method_that_may_rise_an_exception()
except:
pass
else:
if pk:
process_pk()
return
method_to_be_executed_in_case_of_exception_or_pk_is_false()

