try
条语句不会创建新的作用域,但如果对url lib.request.urlopen
的调用引发异常,则不会设置text
.您可能希望在else
子句中包含print(text)
行,以便仅在没有异常时执行它.
try:
url = "http://www.google.com"
page = urllib.request.urlopen(url)
text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
print("Unable to process your request dude!!")
else:
print(text)
如果以后需要使用text
,你真的需要考虑如果分配给page
失败,你不能调用page.read()
,它的值应该是多少.您可以在try
语句之前给它一个初始值:
text = 'something'
try:
url = "http://www.google.com"
page = urllib.request.urlopen(url)
text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
print("Unable to process your request dude!!")
print(text)
或者在else
条款中:
try:
url = "http://www.google.com"
page = urllib.request.urlopen(url)
text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
print("Unable to process your request dude!!")
else:
text = 'something'
print(text)