2

I have tried to search but I couldn't find anything. However I probably just didn't word it right. In the book I am reading. A Python Book by Dave Kuhlman He writes a try:except statement to catch an IOError.

def test():
    infilename = 'nothing.txt'
    try:
        infile = open(infilename, 'r')
        for line in infile:
            print line
    except IOError, exp:
        print 'cannot open file "%s"' % infilename

My question is what is the exp after IOError. what does it do and why is that there?

jpmc26
  • 28,463
  • 14
  • 94
  • 146
Wickie Lee
  • 109
  • 1
  • 7

4 Answers4

5

It provides a variable name for the exception inside the except block:

>>> try:
...     raise Exception('foo')
... except Exception, ex:
...     print ex
...     print type(ex)
...
foo
<type 'exceptions.Exception'>

I personally find the as syntax more clear:

>>> try:
...     raise Exception('foo')
... except Exception as ex:
...     print ex
...     print type(ex)
...
foo
<type 'exceptions.Exception'>

But the as syntax wasn't introduced until 2.6, according to answers in this question.

Community
  • 1
  • 1
jpmc26
  • 28,463
  • 14
  • 94
  • 146
  • Ah, now that makes sense. I have been scratching my head about this for around 30 minutes. And yes I have to agree with you. With the as their it is very clear as to what it is doing with Exception – Wickie Lee Aug 30 '13 at 02:55
  • 1
    +1 and "`, ex`" part (or "`as ex`" part) is optional, if you do not need the exception to be assigned to a variable. – Tadeck Aug 30 '13 at 03:06
1

exp is a variable that the exception object will be assigned to. When an exception is raised, Python creates an exception object containing more information about the error, including a stack trace and often including an error message. This code doesn't actually use exp, so it'd be cleaner to leave it out.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • I agree, that was another reason I was racking my brain over it. I couldn't find anything else involving it. – Wickie Lee Aug 30 '13 at 03:00
1
except: IOError, exp: 

should be like this:

except IOError, exp:

exp stores the error msg , so the value of exp is: No such file or directory:XXX
you can rename it to anything else

Odai Al-Ghamdi
  • 302
  • 2
  • 12
0

It contains an error message, stack trace and other information about the error. Although that specific code excerpt does not actually use the information, it would be relevant in production environments, where error logging is important for debugging.

aspie
  • 43
  • 4