Python 中的条件 except 语句

use*_*889 5 python exception

有没有办法使 except 语句有条件 - 换句话说,仅在条件为真时捕获某种类型的异常?这是我的想法,但好像行不通

try:
  <code>
if condition == True:
  except Exception as e:
    <error handling>
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 9

不,你不能那样做。您可以做的是捕获错误,然后检查 except 块内的条件,并在必要时重新引发:

except Exception as e:
    if not condition:
        raise
Run Code Online (Sandbox Code Playgroud)

  • 在“raise”之后不需要“e” (3认同)