How to catch SystemExit Exception in Python?


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

Example

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

Example

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

Output

It works!

Updated on: 12-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements