python – Difference between calling sys.exit() and throwing exception

python – Difference between calling sys.exit() and throwing exception

sys.exit raises a SystemExit itself so from a purely technical point of view theres no difference between raising that exception yourself or using sys.exit. And yes you can catch SystemExit exceptions like any other exception and ignore it.

So its just a matter of documenting your intent better.

PS: Note that this also means that sys.exit is actually a pretty bad misnomer – because if you use sys.exit in a thread only the thread is terminated and nothing else. That can be pretty annoying, yes.

Theres a small, subtle difference:

import sys

try:
    sys.exit()
except:
    print(Caught)

that except statement catches the exception whereas:

import sys

try:
    sys.exit()
except Exception:
    print(Caught)

exits without error. SystemExit exception (like KeyboardInterrupt) isnt caught by except Exception, but caught by except alone.

So if the caller catches everything with except: (which is bad practice), your sys.exit wont quit but will be considered as an error. Thats why except Exception: is better to be sure to catch all exceptions except CTRL+C and system exit (which are of the BaseException class).

python – Difference between calling sys.exit() and throwing exception

Leave a Reply

Your email address will not be published.