21

I am trying to catch a SystemExit exception in the following fashion:

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

But, it doesn't work.

It does work however when I change my code like that:

try:
    raise SystemExit
except:
    print "success"

As far as I am aware, except Exception as exception should catch any exception. This is how it is described here as well. Why isn't that working for me here?

Community
  • 1
  • 1
Eugene S
  • 6,709
  • 8
  • 57
  • 91

1 Answers1

44

As documented, SystemExit does not inherit from Exception. You would have to use except BaseException.

However, this is for a reason:

The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception.

It is unusual to want to handle "real" exceptions in the same way you want to handle SystemExit. You might be better off catching SystemExit explicitly with except SystemExit.

Adam Nelson
  • 7,932
  • 11
  • 44
  • 64
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Perfect. Thanks! It is very well illustrated in the documentation Exception hierarchy: https://docs.python.org/2/library/exceptions.html#exception-hierarchy – Eugene S Oct 29 '14 at 05:02