2024-05-17 04:03:54 发布
网友
我的代码在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
有可能吗?
提取(重构)语句。利用and和or的魔力来决定何时短路。
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
您必须将这个分开try块:
try
try: code a except ExplicitException: pass try: code b except ExplicitException: try: code c except ExplicitException: try: code d except ExplicitException: pass
这假设您只想在code b失败时运行code c。
code b
code c
如果需要运行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
我在这里使用except ExplicitException,因为盲目忽略所有异常是一个好的做法。否则,您将忽略MemoryError、KeyboardInterrupt和SystemExit,您通常不希望忽略或拦截这些,而无需重新启动或有意识地处理它们。
except ExplicitException
MemoryError
KeyboardInterrupt
SystemExit
您可以使用fuckit模块。 用@fuckitdecorator将代码包装在函数中:
@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
提取(重构)语句。利用
and
和or
的魔力来决定何时短路。您必须将这个分开
try
块:这假设您只想在
code b
失败时运行code c
。如果需要运行
code c
而不考虑,则需要逐个放置try
块:我在这里使用
except ExplicitException
,因为盲目忽略所有异常是一个好的做法。否则,您将忽略MemoryError
、KeyboardInterrupt
和SystemExit
,您通常不希望忽略或拦截这些,而无需重新启动或有意识地处理它们。您可以使用fuckit模块。
用
@fuckit
decorator将代码包装在函数中:相关问题 更多 >
编程相关推荐