如何在 try/except 块中公开变量? [英] How to make a variable inside a try/except block public?
问题描述
如何将 try/except 块中的变量设为公开?
How can I make a variable inside the try/except block public?
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' 未定义
NameError: name 'text' is not defined
如何使变量文本在 try/except 块之外可用?
How can I make the variable text available outside of the try/except block?
推荐答案
try
语句不会创建新的作用域,但如果调用,则不会设置 text
to url lib.request.urlopen
引发异常.您可能需要 else
子句中的 print(text)
行,以便它仅在没有异常时才执行.
try
statements do not create a new scope, but text
won't be set if the call to url lib.request.urlopen
raises the exception. You probably want the print(text)
line in an else
clause, so that it is only executed when there is no exception.
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
语句之前给它一个初始值:
If text
needs to be used later, you really need to think about what its value is supposed to be if the assignment to page
fails and you can't call page.read()
. You can give it an initial value prior to the try
statement:
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)
这篇关于如何在 try/except 块中公开变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!