如何在 try/except block 中公开变量?
import urllib.request
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)
此代码返回错误
NameError: name 'text' is not defined
如何使变量文本在 try/except block 之外可用?
最佳答案
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)
关于python - 如何在 try/except block 中公开变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25666853/