try
语句不会创建新范围,但如果调用引发异常text
则不会设置。url lib.request.urlopen
您可能希望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:
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)