多个尝试代码在一个块 [英] 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
这样可能吗?
推荐答案
你必须让这个>分开 尝试
块:
You'll have to make this separate try
blocks:
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
try:
code c
except ExplicitException:
try:
code d
except ExplicitException:
pass
假设您想运行代码c
只有如果代码b
失败。
This assumes you want to run code c
only if code b
failed.
如果您需要运行代码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
as否则,你通常不想忽视或拦截没有某种重新提高或有意识的理由来处理这些。
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屋!