一个块中的多个尝试代码 [英] Multiple try codes in one block
问题描述
我在 try 块中的代码有问题.为方便起见,这是我的代码:
I have a problem with my code in the try block. To make it easy this is my code:
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
这样的事情有可能吗?
推荐答案
你必须让这个单独 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
only.
This assumes you want to run code c
only if code b
failed.
如果你需要运行code c
不管,你需要一个接一个地放置try
块:
If you need to run code c
regardless, you need to put the try
blocks one after the other:
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
-提出或有意识地处理这些问题.
I'm using except ExplicitException
here because it is never a 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.
这篇关于一个块中的多个尝试代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!