1

I got this code while I was looking into urllib2.

import urllib2
req = urllib2.Request('http://www.baibai.com')
try: urllib2.urlopen(req)
except urllib2.URLError,e: 
    print e.reason

I got confused when and whether to use e in the statement except urllib2.URLError, e: since it seems OK to use except urllib2.URLError: (without e).

Can every except statement have the format except:XXXX, e or just in some cases?

Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46

1 Answers1

4

Using the syntax urllib2.URLError, e you have access to the exception that was thrown (for example to print the message). If you only use except urllib2.URLError you indicate that you want to do something when a URLError is thrown, but you don't need the actual exception object.

Note that you are using a outdated python version because you are using , in your except blocks. Python 3+ requires as instead of , (except urllib2.URLError as e) while only Python 2.5- uses the , syntax.

I recommend you learn a bit about exceptions. Here's the official documentation on exceptions. More information about , vs as can be found on this StackOverflow answer.

Community
  • 1
  • 1
molenzwiebel
  • 886
  • 6
  • 21