Simple way of handling errors

Steven D'Aprano steven at
Thu May 7 04:41:29 CEST 2009

On Wed, 06 May 2009 16:40:19 -0700, TomF wrote:

> 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)

Functions never fail silently in Python. (At least built-in functions 
never fail silently. Functions you write yourself can do anything you 

The canonical way of doing "open or die" in Python is to just call open:

f = open(filename)

If it fails, you get both a straight-forward error message and a useful 

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'foomanchu'

The only reason you would bother going to the time and effort of catching 
the error, printing your own error message, and then exiting, is if you 
explicitly want to hide the traceback from the user.

Oh, and if you do that, I recommend that you print to stderr instead of 

    print >>sys.stderr, "open(%s): got %s" % (file, err.strerror)


    sys.stderr.write("open(%s): got %s\n" % (file, err.strerror))


More information about the Python-list mailing list