Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch SystemExit Exception in Python?

I am trying to handle SystemExit Exception in the following manner

try:
    raise SystemExit
except Exception:
    print "It works!"

However, it does not work

How do I handle the SystemExit Exception?


1 Answer
Rajendra Dharmkar

In python documentation, SystemExit is not a subclass of Exception class. BaseException class is the base class of SystemExit. So in given code, we replace the Exception with BaseException to make the code work

try:
raise SystemExit
except BaseException:
print "It works!"

OUTPUT

It works!

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

We would rather write the code this way

try:
raise SystemExit
except SystemExit:
print "It works!"

OUTPUT

It works!

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.