28

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?

1 Answer 1

53

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thanks! It is very well illustrated in the documentation Exception hierarchy: docs.python.org/2/library/exceptions.html#exception-hierarchy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.