Hiding tracebacks from end-users

kyosohma at gmail.com kyosohma at gmail.com
Tue Oct 23 19:57:02 CEST 2007

On Oct 23, 11:07 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> I'm writing a command-line application that is meant to be relatively
> user friendly to non-technical users.
> (Some wags might like to say that "user friendly" and "command-line
> application" are, by definition, contradictory. I disagree.)
> Consequently, I'd like to suppress Python's tracebacks if an error does
> occur, replacing it with a more friendly error message. I'm doing
> something like this:
> try:
>     setup()
>     do_something_useful()
> except KeyboardInterrupt:
>     print >>sys.stderr, "User cancelled"
>     sys.exit(2)
> except Exception, e:
>     if expert_mode:
>         # experts get the full traceback with no hand-holding.
>         raise
>     else:
>         # print a more friendly error message
>         if isinstance(e, AssertionError):
>             msg = "An unexpected program state occurred"
>         elif isinstance(e, urllib2.HTTPError):
>             msg = "An Internet error occurred"
>         else:
>             # catch-all for any other exception
>             msg = "An error occurred"
>         print>>sys.stderr, msg
>         print>>sys.stderr, e
>         sys.exit(1)
> else:
>     sys.exit(0)
> Is this a good approach? Is there another way to suppress the traceback
> and just print the error message?
> --
> Steven.

I think this is a good approach too. But why are you using If
statements for some errors? You should be able to do something like

    do something
except AssertionError:
    do something
except ZeroDivisionError:
    do something
except urllib2.HTTPError:
    do something

etc, etc...

If you know what errors to expect, make them into a specific except
block. And leave the catchall on there for the exceptions you've


More information about the Python-list mailing list