arv*_*urs 53 python exception-handling exception try-catch except
我在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
Run Code Online (Sandbox Code Playgroud)
这样的事情可能吗?
Mar*_*ers 75
你必须制作这个单独的 try块:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
try:
code c
except ExplicitException:
try:
code d
except ExplicitException:
pass
Run Code Online (Sandbox Code Playgroud)
这是假设你想运行code c 仅如果code b失败.
如果你需要运行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
Run Code Online (Sandbox Code Playgroud)
我在except ExplicitException这里使用是因为盲目地忽略所有异常从来都不是一个好习惯.你会被忽略MemoryError,KeyboardInterrupt并且SystemExit还有否则,你通常不希望没有某种形式再次加注或意识理性处理那些无视或拦截.
Mos*_*hri 14
你可以使用fuckit模块.
使用@fuckit装饰器将代码包装在一个函数中:
@fuckit
def func():
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
Run Code Online (Sandbox Code Playgroud)
提取(重构)您的陈述。和使用魔法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
Run Code Online (Sandbox Code Playgroud)
如果您不想链接(大量)try-except 子句,您可以在循环中尝试您的代码并在第一次成功时中断。
可以放入函数的代码示例:
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)
Run Code Online (Sandbox Code Playgroud)
直接在当前范围内使用任意代码(语句)的示例:
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)
Run Code Online (Sandbox Code Playgroud)
你可以尝试一个for循环
for func,args,kwargs in zip([a,b,c,d],
[args_a,args_b,args_c,args_d],
[kw_a,kw_b,kw_c,kw_d]):
try:
func(*args, **kwargs)
break
except:
pass
Run Code Online (Sandbox Code Playgroud)
这样你就可以循环任意数量的函数,而不会让代码看起来很难看
| 归档时间: |
|
| 查看次数: |
78306 次 |
| 最近记录: |