【问题标题】:Python: do something for every Exception raisedPython:为每个引发的异常做一些事情
【发布时间】:2015-02-24 02:16:54
【问题描述】:

Python 的 try...except 构造允许捕获多个异常并对每个异常执行相同的操作 (except (Exception1, Exception2, ...):),无论是否引发异常 (finally:) 都可以执行相同的操作并执行仅当引发异常时(else:)。有没有办法分别处理每个异常,但如果发生任何异常,然后做同样的事情(例如sys.exit())?目前我正在为每个except单独使用这个调用:

try:
    np.loadtxt(filename, ...)
except ValueError as e:
     # Handle the ValueError with a custom message here
     sys.exit(1)
except FileNotFoundError as e:
     # Handle missing file here
     sys.exit(1)
except SomeOtherErrorThatMightConceivablyBeRaised:
     # Handle it
     sys.exit(1)

【问题讨论】:

  • 将其包装在一个函数中,并将return 放在else 子句中。之后进行您需要的任何处理。

标签: python exception error-handling


【解决方案1】:

您可以在括号中对异常进行分组:

try:
    np.loadtxt(filename, ...)
except (ValueError, 
        FileNotFoundError, 
        SomeOtherErrorThatMightConceivablyBeRaised) as e:
    # Handle the ValueError with a custom message here
    sys.exit(1)

【讨论】:

  • 问题是我想对每个异常before sys.exit(1)做一些不同的事情。
  • 您可以按照 Skylor 的建议在括号中对多个异常进行分组,并使用 if 语句来确定“catch”块中的异常类型。看这里:stackoverflow.com/questions/4329453/…
猜你喜欢
  • 2015-10-20
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
相关资源
最近更新 更多