Python SystemExit Exception Explained

Artem Rys
python4you
Published in
1 min readDec 11, 2018

--

Some Python magic around sys.exit() function.

Photo by Christopher Burns on Unsplash

Recently I’ve been at the interview for one big Israel startup.
They asked me to read the code below and say what will be in the output.

  • What do you think to be the output after running this code snippet?
  • Is it depend on the body of some_func function?

Let’s try to figure out what is going on within this small piece of code.

Did you know that sys.exit(code) raises SystemExit exception?

  1. Lines 10–11 will raise an SystemExit exception

2. SystemExit exception is caught by except statement in line 12

3. Exception will be printed

4. sys.exit(1) in line 14 raises an exception

5. Code in finally statement in line 16 is executed and Out is printed out

6. And finally, the statement in line 22 is executed because of exception from sys.exit(1) and Out2 is printed

--

--

Artem Rys
python4you

Principal Software Engineer @ Splunk. Writing about Python, GitHub and Splunk.