On 13/07/12 04:16:53, Steven D'Aprano wrote: > On Thu, 12 Jul 2012 16:37:42 +0100, andrea crotti wrote: > >> 2012/7/12 John Gordon <gor...@panix.com>: >>> In <mailman.2043.1342102625.4697.python-l...@python.org> andrea crotti >>> <andrea.crott...@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?
It may be that the function you're calling found a problem that the author thinks is so grave that they shouldn't give you an opportunity to deal with it. If that's the case, I would be inclined to think that they are wrong. > 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. I would agree if you had said "in production code". If you are investigating why a third-party function is stopping your interpreter, then catching BaseException may tell you that the code is raising the wrong kind of Exception. Once you know what kind the function is raising, you should catch only that particular excpetion subclass. > 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 If you want to find out who is raising the exception, you could try this: except SystemExit: import traceback traceback.print_exc() That will print a complete stack trace. If you only need to know what kind of exception you have, you can do: print(repr(e)) A simple print(e) will print str(e), which in the case of SystemExit, is an empty string. That's not very informative. > 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?") Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list