Alex Rivera | Logout

Why "except Exception" doesn't catch SystemExit?

Asked 2011-04-19T09:49:56.373
11

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.

Edit
Report

1 Answer

11

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.

answered 2011-04-19T10:01:11.930

Your Answer