Simple way of handling errors

TomF tomf.sessile at gmail.com
Thu May 7 05:21:38 CEST 2009


On 2009-05-06 19:41:29 -0700, Steven D'Aprano 
<steven at REMOVE.THIS.cybersource.com.au> said:

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

Well, yes, I'm aware that if you don't handle errors Python barfs out a 
backtrace.

> If it fails, you get both a straight-forward error message and a useful
> traceback:
> 
> 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.

Well, to me, exposing the user to such raw backtraces is 
unprofessional, which is why I try to catch user-caused errors.  But I 
suppose I have an answer to my question.

Thanks,
-Tom




More information about the Python-list mailing list