[英]Catch exceptions within context manager
Trying to understand how I should catch/handle exceptions of a context manager:试图了解我应该如何捕获/处理上下文管理器的异常:
import contextlib
import urllib
with contxtlib.closing( urllib.request.urlopen(some_url) ) as resp:
return resp.read()
I know that upon exiting the context manager, even if any errors occurred, the context manager will close.我知道在退出上下文管理器时,即使发生任何错误,上下文管理器也会关闭。 For the example above, how could I catch the closing
and urlopen
exceptions given that they are within a context manager?对于上面的示例,鉴于它们位于上下文管理器中,我如何捕获closing
和urlopen
异常? Is there a way for me to use try... except
to catch and handle all exceptions for both closing
and urlopen
?有没有办法让我使用try... except
捕获和处理closing
和urlopen
的所有异常?
from contextlib import closing
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
try:
with closing(urlopen(some_url)) as resp:
return resp.read()
except (HTTPError, URLError, Exception) as err:
print(err)
# handle exception(s)
The contextlib.closing()
context manager calls the close() method. contextlib.closing()
上下文管理器调用 close() 方法。 As can be seen in the docs , you do not have to explicitly close it yourself (replaced page
with obj
for context):从文档中可以看出,您不必自己显式关闭它(用obj
替换page
作为上下文):
Even if an error occurs, obj.close() will be called when the with block is exited.即使发生错误,退出 with 块时也会调用 obj.close()。
For the urllib.request.urlopen
, see the approaches on catching HTTPError or URLError
with urlopen
对于urllib.request.urlopen
,请参阅使用urlopen
捕获HTTPError or URLError
的方法
Follow-up reading:后续阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.