printing error message from an Exception

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Dec 10 05:33:13 EST 2010


mark jason wrote:
> On Dec 10, 11:55 am, Steven D'Aprano <steve
> +comp.lang.pyt... at pearwood.info> wrote:
>   
>>     # By the way, IOError is not the only exception you could see.
>>     
>
>
> thanks for the help Steven. Is it OK to catch Exception instead of
> IOError ?
> In some operation which can cause many errors ,can I use the
> following?
>
> try:
>     do_something()
> except Exception,e:
>     display_message(e.args)
>     handle_exception(e)
>
>
> thanks,
> mark
>   
You shouldn't.

If you want to handle an exception, you need to know about it. What if 
your handle_exception meets some exception it does not know how to handle ?

People are sometimes using bare try except clause to say 'look ! my 
function never crash !'. True but it usually has an unpredictable 
behavior upon exception being raised, and that is much worse that a 
clean uncought exception.


What you can do :

try:
    do_something()
except IOError:
    # handler IOerror
except KeyboardInterrupt:
    print 'stopping...'
    sys.exit(0)
except NotImplementedError:
    # handler missing implementation

Everything else should be kept uncought.

JM



More information about the Python-list mailing list