ins*_*get 2521 python exception-handling exception
我知道我能做到:
try:
# do something that may fail
except:
# do this if ANYTHING goes wrong
Run Code Online (Sandbox Code Playgroud)
我也可以这样做:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreTooShortException:
# stand on a ladder
Run Code Online (Sandbox Code Playgroud)
但如果我想在两个不同的例外中做同样的事情,我现在能想到的最好的就是这样做:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreBeingMeanException:
# say please
Run Code Online (Sandbox Code Playgroud)
有什么办法我可以做这样的事情(因为两个例外的行动都是say please):
try:
# do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
# say please
Run Code Online (Sandbox Code Playgroud)
现在这真的不起作用,因为它符合以下语法:
try:
# do something that may fail
except Exception, e:
# say please
Run Code Online (Sandbox Code Playgroud)
因此,我努力捕捉这两个截然不同的例外并没有完全实现.
有没有办法做到这一点?
ber*_*nie 3431
从Python文档:
例如,except子句可以将多个异常命名为带括号的元组
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
Run Code Online (Sandbox Code Playgroud)
或者,仅适用于Python 2:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
Run Code Online (Sandbox Code Playgroud)
使用逗号将变量与变量分开仍然可以在Python 2.6和2.7中使用,但现在已弃用,但在Python 3中不起作用; 现在你应该使用as.
Aar*_*all 278
如何在一行中捕获多个异常(块除外)
做这个:
try:
may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
handle(error) # might log or have some other default behavior...
Run Code Online (Sandbox Code Playgroud)
由于旧语法使用逗号将错误对象分配给名称,因此必须使用括号.该as关键字用于分配.您可以使用任何名称作为错误对象,我error个人更喜欢.
要以与Python当前和向前兼容的方式执行此操作,您需要使用逗号分隔异常并用括号括起它们,以区别于将异常实例分配给变量名的早期语法,方法是遵循要捕获的异常类型逗号.
这是一个简单用法的例子:
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
我只指定了这些异常,以避免隐藏错误,如果遇到错误,我希望完整的堆栈跟踪.
这在此处记录:https://docs.python.org/tutorial/errors.html
您可以将异常分配给变量(e通常情况下,但如果您有长时间的异常处理,或者您的IDE仅突出显示大于此的选项,您可能更喜欢更详细的变量,就像我的那样.)该实例具有args属性.这是一个例子:
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError) as err:
print(err)
print(err.args)
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
请注意,在Python 3中,err当except块结束时,对象超出范围.
您可能会看到用逗号分配错误的代码.这种用法是Python 2.5及更早版本中唯一可用的形式,不推荐使用,如果您希望代码在Python 3中向前兼容,则应更新语法以使用新表单:
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
print err
print err.args
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
如果您在代码库中看到逗号名称分配,并且您使用的是Python 2.5或更高版本,请切换到新的方法,以便在升级时代码保持兼容.
suppress上下文管理器接受的答案实际上是4行代码,最少:
try:
do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
Run Code Online (Sandbox Code Playgroud)
在try,except,pass线可以与单线处理抑制上下文管理器,可以在Python 3.4:
from contextlib import suppress
with suppress(IDontLikeYouException, YouAreBeingMeanException):
do_something()
Run Code Online (Sandbox Code Playgroud)
因此,当您想要pass处理某些异常时,请使用suppress.
fed*_*qui 44
一个
try语句可能有不止一个,除了子句,分别指定处理不同的异常.最多将执行一个处理程序.处理程序仅处理相应try子句中发生的异常,而不处理同一try语句的其他处理程序中的异常.except子句可以将多个异常命名为带括号的元组,例如:Run Code Online (Sandbox Code Playgroud)except (RuntimeError, TypeError, NameError): pass请注意,这个元组周围的括号是必需的,因为除了
ValueError, e:用于通常except ValueError as e:在现代Python中编写的语法(如下所述).仍然支持旧语法以实现向后兼容性.这意味着except RuntimeError, TypeError不等于,except (RuntimeError, TypeError):但except RuntimeError asTypeError:不是你想要的.
whi*_*ard 30
如果经常使用大量异常,则可以预先定义元组,因此不必多次重新键入它们.
#This example code is a technique I use in a library that connects with websites to gather data
ConnectErrs = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)
def connect(url, data):
#do connection and return some data
return(received_data)
def some_function(var_a, var_b, ...):
try: o = connect(url, data)
except ConnectErrs as e:
#do the recovery stuff
blah #do normal stuff you would do if no exception occurred
Run Code Online (Sandbox Code Playgroud)
笔记:
如果您还需要捕获除预定义元组之外的其他异常,则需要定义另一个除块之外的异常.
如果您无法容忍全局变量,请在main()中定义它并在需要的地方传递它...
Gio*_*ous 20
从 Python 3.11 开始,您可以利用except*用于处理多个异常的子句。
PEP-654 引入了一种新的标准异常类型,称为ExceptionGroup,它对应于一起传播的一组异常。可以ExceptionGroup使用新except*语法来处理。该*符号表示每个子句可以处理多个异常except*。
例如,您可以处理多个异常
try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅PEP-654。
M.U*_*man 13
其中一种方法是..
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
Run Code Online (Sandbox Code Playgroud)
另一种方法是创建执行except块执行任务的方法,并通过except你编写的所有块调用它.
try:
You do your operations here;
......................
except Exception1:
functionname(parameterList)
except Exception2:
functionname(parameterList)
except Exception3:
functionname(parameterList)
else:
If there is no exception then execute this block.
def functionname( parameters ):
//your task..
return [expression]
Run Code Online (Sandbox Code Playgroud)
我知道第二个不是最好的方法,但我只是展示了做这件事的方法.
| 归档时间: |
|
| 查看次数: |
724813 次 |
| 最近记录: |