Python 一个块中的多个尝试代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17322208/
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
Multiple try codes in one block
提问by arvidurs
I have a problem with my code in the try block. To make it easy this is my code:
我在 try 块中的代码有问题。为方便起见,这是我的代码:
try:
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
except:
pass
Is something like this possible?
这样的事情可能吗?
采纳答案by Martijn Pieters
You'll have to make this separatetry
blocks:
你必须制作这个单独的try
块:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
try:
code c
except ExplicitException:
try:
code d
except ExplicitException:
pass
This assumes you want to run code c
onlyif code b
failed.
这是假设你想运行code c
仅如果code b
失败。
If you need to run code c
regardless, you need to put the try
blocks one after the other:
如果你需要运行code c
不管,你需要把try
块一前一后:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
pass
try:
code c
except ExplicitException:
pass
try:
code d
except ExplicitException:
pass
I'm using except ExplicitException
here because it is nevera good practice to blindly ignore all exceptions. You'll be ignoring MemoryError
, KeyboardInterrupt
and SystemExit
as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.
我在except ExplicitException
这里使用是因为盲目忽略所有异常从来都不是一个好习惯。你会被忽略MemoryError
,KeyboardInterrupt
并且SystemExit
还有否则,你通常不希望忽略或没有某种形式再次加注或意识理性处理这些拦截。
回答by Inbar Rose
Extract (refactor) your statements. And use the magic of and
and or
to decide when to short-circuit.
提取(重构)您的语句。和使用魔法and
和or
何时决定短路。
def a():
try: # a code
except: pass # or raise
else: return True
def b():
try: # b code
except: pass # or raise
else: return True
def c():
try: # c code
except: pass # or raise
else: return True
def d():
try: # d code
except: pass # or raise
else: return True
def main():
try:
a() and b() or c() or d()
except:
pass
回答by kxr
If you don't want to chain (a huge number of) try-except clauses, you may try your codes in a loop and break upon 1st success.
如果您不想链接(大量)try-except 子句,您可以在循环中尝试您的代码并在第一次成功时中断。
Example with codes which can be put into functions:
可以放入函数的代码示例:
for code in (
lambda: a / b,
lambda: a / (b + 1),
lambda: a / (b + 2),
):
try: print(code())
except Exception as ev: continue
break
else:
print("it failed: %s" % ev)
Example with arbitrary codes (statements) directly in the current scope:
直接在当前范围内使用任意代码(语句)的示例:
for i in 2, 1, 0:
try:
if i == 2: print(a / b)
elif i == 1: print(a / (b + 1))
elif i == 0: print(a / (b + 2))
break
except Exception as ev:
if i:
continue
print("it failed: %s" % ev)
回答by Mostafa Bahri
回答by ZF007
Lets say each code is a function and its already written then the following can be used to iter through your coding list and exit the for-loop when a function is executed without error using the "break".
假设每个代码都是一个函数,并且它已经编写好了,那么下面的代码可用于遍历您的编码列表,并在使用“break”正确执行函数时退出 for 循环。
def a(): code a
def b(): code b
def c(): code c
def d(): code d
for func in [a(), b(), c(), d()]: # change list order to change execution order.
try:
func
break
except Exception as err:
print (err)
continue
I used "Exception " here so you can see any error printed. Turn-off the print if you know what to expect and you're not caring (e.g. in case the code returns two or three list items (i,j = msg.split('.')).
我在这里使用了“异常”,因此您可以看到打印的任何错误。如果您知道会发生什么并且您不关心(例如,如果代码返回两个或三个列表项(i,j = msg.split('.')),请关闭打印。
回答by Yesh
You could try a for loop
你可以试试 for 循环
try : a()
except: pass
for func in [b,c,d]:
try:
func()
break
except:
pass
This way you can loop as many functions as you want without making the code look ugly
这样你就可以循环尽可能多的函数,而不会让代码看起来很丑