Cannot catch Python SystemExit exception

I am trying to catch a SystemExit exception like this:

 try: raise SystemExit except Exception as exception: print "success" 

But that does not work.

It really works when I change my code as follows:

 try: raise SystemExit except: print "success" 

As far as I know, except Exception as exception should catch any exception. Here is how it is described here . Why does this not work for me here?

+8
python exception exception-handling
source share
1 answer

As documented , SystemExit does not inherit from Exception. You will need to use except BaseException .

However, this is for some reason:

The exception is inherited from BaseException instead of StandardError or Exception, so that it does not accidentally fall into code that catches the exception.

It is unusual to want to handle "real" exceptions the way you want to handle SystemExit. You might be better off not using SystemExit with except SystemExit .

+18
source share

All Articles