Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "except Exception" doesn't catch SystemExit?

isinstance(SystemExit(1), Exception) evals to True, but this snippet prints "caught by bare except SystemExit(1,)".

try:
    sys.exit(0)
except Exception, e:
    print 'caught by except Exception', str(e)
except:
    print 'caught by bare except', repr(sys.exc_info()[1])

My testing environment is Python 2.6.

like image 244
Gary Shi Avatar asked Apr 19 '11 09:04

Gary Shi


3 Answers

isinstance(SystemExit(1), Exception) is False on Python 2.6. Exception hierarchy in this version of Python was changed since Python 2.4.

E.g. KeyboardInterrupt is not subclass of Exception any more.

See more info http://docs.python.org/release/2.6.6/library/exceptions.html#exception-hierarchy

like image 199
Roman Bodnarchuk Avatar answered Sep 22 '22 06:09

Roman Bodnarchuk


SystemExit derives from BaseException directly rather than from Exception.

Exception is the parent "All built-in, non-system-exiting exceptions"

SystemExit is a "system exiting exception" (by definition) and therefore doesn't derive from Exception. In your example, if you used BaseException, it would work as per your original assumptions.

like image 23
Noufal Ibrahim Avatar answered Sep 22 '22 06:09

Noufal Ibrahim


Your error is in the very first sentence of your question:

>>> isinstance(SystemExit(1), Exception)
False

SystemExit is not a subclass of Exception.

like image 36
Sven Marnach Avatar answered Sep 20 '22 06:09

Sven Marnach