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)
This code returns an error NameError: name 'text' is not defined
.
How can I make the variable text available outside of the try/except block?
try
statements do not create a new scope, buttext
won't be set if the call tourl lib.request.urlopen
raises the exception. You probably want theprint(text)
line in anelse
clause, so that it is only executed when there is no exception.If
text
needs to be used later, you really need to think about what its value is supposed to be if the assignment topage
fails and you can't callpage.read()
. You can give it an initial value prior to thetry
statement:or in the
else
clause:As answered before there is no new scope introduced by using
try except
clause, so if no exception occurs you should see your variable inlocals
list and it should be accessible in current (in your case global) scope.In module scope (your case)
locals() == globals()
Just declare the variable
text
outsidetry
except
block,