printing error message from an Exception
Peter Otten
__peter__ at web.de
Fri Dec 10 04:15:05 EST 2010
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'
>
> 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?
> Also ,what should I do about the UnboundLocalError?
You are mixing two things here:
(1) print an error message when the file cannot be opened
(2) ensure that the file will always be closed
If you attack both aspects separately they become simpler:
# 1
try:
f = open(...)
except IOError as e:
print "Failed", e
# 2a
f = open(...)
try:
print "opened"
finally:
f.close()
which can be simplified to
# 2b
with open(...) as f:
print "opened"
Putting 1 and 2b together:
try:
with open(...) as f:
print "opened"
except IOError as e:
print "Failed", e
There is a disadvantage though: an IOError that is raised in the with-suite
will also be caught. If you're concerned about that you can use:
try:
f = open(...)
except IOError as e:
print "Failed", e
else:
with contextlib.closing(f):
print "opened"
More information about the Python-list
mailing list