mwo*_*e02 7 python exception-handling urllib2
这特别适用于urllib2,但更常见的是自定义异常处理.如何通过引发的异常将其他信息传递给另一个模块中的调用函数?我假设我会使用自定义异常类重新加注,但我不确定技术细节.
我没有用我尝试过的和失败的方式污染示例代码,而是将其简单地呈现为一个空白的板块.我的最终目标是让样本中的最后一行起作用.
#mymod.py
import urllib2
def openurl():
req = urllib2.Request("http://duznotexist.com/")
response = urllib2.urlopen(req)
#main.py
import urllib2
import mymod
try:
mymod.openurl()
except urllib2.URLError as e:
#how do I do this?
print "Website (%s) could not be reached due to %s" % (e.url, e.reason)
Run Code Online (Sandbox Code Playgroud)
您可以添加信息,然后重新引发异常.
#mymod.py
import urllib2
def openurl():
req = urllib2.Request("http://duznotexist.com/")
try:
response = urllib2.urlopen(req)
except urllib2.URLError as e:
# add URL and reason to the exception object
e.url = "http://duznotexist.com/"
e.reason = "URL does not exist"
raise e # re-raise the exception, so the calling function can catch it
#main.py
import urllib2
import mymod
try:
mymod.openurl()
except urllib2.URLError as e:
print "Website (%s) could not be reached due to %s" % (e.url, e.reason)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7858 次 |
| 最近记录: |