Operators
try does not create a new scope, but text will not be set if the url lib.request.urlopen call url lib.request.urlopen throws an exception. You probably need the print(text) in the else clause, so it will only be executed if 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)
If text needs to be used later, you really need to think about what its value should be if the page assignment fails, and you cannot call page.read() . You can give it an initial value before the 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)
or in 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)
chepner
source share