Python – How to Catch sys.exit()
I wanted to catch a sys.exit() call in my code (using Python 2.5) and handle it but alas even this wasn’t working:
import sys
try:
sys.exit()
except Exception,Err:
print 'hi'
It would just exit the script.
I found this is the way to go when you truly want to capture all exceptions:
try:
sys.exit()
except BaseException,Err:
print 'hi'
Please correct me if I’m missing anything. Are there any exceptions I still won’t catch?
Is there some reason you’re not just doing:
try:
sys.exit()
except:
print 'hi'
?This annoys pylint, but AFAIK it's the only guaranteed way to catch all exceptions. (Runtime exceptions are supposed to extend the Exception base class, but not all code does it. pyserial, I'm looking at you.)
I’m assuming that you’re using Python 2.5.
Check out this page:
http://docs.python.org/whatsnew/pep-352.html
KeyboardInterrupt is the other exception
that won’t be caught by your
‘except Exception:’ clause.
As sri said, if you really want to catch all exceptions in Python 2.5, use BaseException instead of Exception.
Thanks, so I guess I want BaseException. Good to know.
Nope, if you really want to catch all exceptions, you also have to remember that you can raise *strings* as exceptions too.