adding a simulation mode

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jul 13 04:16:53 CEST 2012


On Thu, 12 Jul 2012 16:37:42 +0100, andrea crotti wrote:

> 2012/7/12 John Gordon <gordon at panix.com>:
>> In <mailman.2043.1342102625.4697.python-list at python.org> andrea crotti
>> <andrea.crotti.0 at gmail.com> writes:
>>
>>> Well that's what I thought, but I can't find any explicit exit
>>> anywhere in shutil, so what's going on there?
>>
>> Try catching SystemExit specifically (it doesn't inherit from
>> Exception, so "except Exception" won't catch it.)
>>
> 
> Ah yes that actually works, but I think is quite dodgy, why was it done
> like this?

Built-in exceptions SystemExit, KeyboardInterrupt and GeneratorExit 
deliberately do not inherit from Exception since they are not meant to be 
caught by "catch-all" try...except Exception clauses.

You can see the exception hierarchy here:

http://docs.python.org/library/exceptions.html#exception-hierarchy

Please do NOT catch BaseException, since that is the wrong thing to do. 
If you must catch SystemExit, KeyboardInterrupt, etc. they you should do 
so as separate catch clauses:

try:
    main()
except SystemExit as e:
    print(e)  # see if we can find out who is raising this
except KeyboardInterrupt:
    print("Mwahahaha my pretty, you cannot cancel this!!!")
    print("...er, now what do I do?")
except Exception:
    print("why am I catching exceptions I can't recover from?")


-- 
Steven



More information about the Python-list mailing list