Simple way of handling errors

TomF tomf.sessile at gmail.com
Thu May 7 01:40:19 CEST 2009


As a relative newcomer to Python, I like it a lot but I'm dismayed at 
the difficulty of handling simple errors.  In Perl if you want to 
anticipate a file-not-found error you can simply do:

open($file)  or die("open($file): $!");

and you get an intelligible error message.  In Python, to get the same 
thing it appears you need at least:

try:
    f=open(file)
except IOError, err:
    print "open(%s): got %s" % (file, err.strerror)
    exit(-1)

Is there a simpler interface or idiom for handling such errors?  I 
appreciate that Python's exception handling is much more sophisticated 
but often I don't need it.

-Tom




More information about the Python-list mailing list