Simple way of handling errors

Steven D'Aprano steven at
Wed May 6 23:38:22 EDT 2009

On Wed, 06 May 2009 20:21:38 -0700, TomF wrote:

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

That depends on your audience. Not every program is written to be used 
for a technical incompetent audience. Some users actually *want* to see 
the errors.

But certainly there are large classes of applications where you do want 
to suppress the traceback. That's why I said "if you explicitly want to 
hide the traceback from the user" rather than "don't do this".

The idiom I use is to wrap the *entire* application in a single 
try...except block, and then put all your user-friendly error handling in 
one place, instead of scattered over the entire application:

except KeyboardInterrupt, SystemExit:
except Exception, e:
    print >>sys.stderr, str(e)

Hope this helps.


More information about the Python-list mailing list