printing error message from an Exception

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Dec 10 01:55:27 EST 2010


On Thu, 09 Dec 2010 22:16:17 -0800, mark jason wrote:

> hi
> I was trying out some file operations and was trying to open a non
> existing file as below
> 
> def do_work(filename):
>     try:
>         f = open(filename,"r");
>         print 'opened'
>     except IOError, e:
>         print 'failed',e.message
>     finally:
>         f.close()
>         print 'closed'


The problem is, you try to close a file that not only hasn't been opened, 
but the name f isn't bound to a value:

>>> do_work('no such file')
failed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in do_work
UnboundLocalError: local variable 'f' referenced before assignment



> if __name__=='__main__':
>     do_work("C:\code\misc.txt")   # there is no such file
> 
> I am getting an error and a warning
> 
> DeprecationWarning: BaseException.message has been deprecated as of
> Python 2.6
>   print 'failed',e.message
> 
> UnboundLocalError: local variable 'f' referenced before assignment
> 
> Is there a way to overcome the DeprecationWarning? I wanted to print the
> error message from the IOError.How do I do this? 

Generally, the best way to print error messages is to print the *entire* 
error message, including the traceback. You do that by just not catching 
the exception at all.

But for the times you do need to do something else with the exception, 
instead of exception.message, look at exception.args. This will be a 
tuple of one or more items, the first item should be the error message.


> Also ,what should I do about the UnboundLocalError?

Use finally for things which must be done regardless of whether or not 
the previous operation succeeded, not for things that should only be done 
if the previous operation succeeded but not if it failed.

def do_work(filename):
    try:
        f = open(filename,"r");
        print 'opened'
    except IOError, e:
    # By the way, IOError is not the only exception you could see.
        print 'failed', e.args
    else:
        f.close()
        print 'closed'


Or, slightly more useful:

def do_work(filename):
    s = ''
    try:
        f = open(filename,"r");
        print 'opened'
    except IOError, e:
    # By the way, IOError is not the only exception you could see.
        print 'failed', e.args
    else:
        try:
            s = f.read()
        finally:
            f.close()
            print 'closed'
    print s



-- 
Steven



More information about the Python-list mailing list