Python SystemExit Exception Explained
Some Python magic around sys.exit()
function.
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)
raisesSystemExit
exception?
- 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