Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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.

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

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top