0
from sys import exit

try:
   print("try")
   exit(0)
except:
   print("except")
finally:
   print("finally")

The program should have terminated in exit(0), isn't it? Why was its output :

try
except
finally

prabesh013
  • 15
  • 2

2 Answers2

0

Because sys.exit just raises SystemExit, and it's SystemExit reaching the top stack frame (in the main thread) which causes the interpreter to shut down.

That is one of the reasons why you generally should not catch a bare except (aka should generally at least use except Exception): it'll catch SystemExit (and KeyboardInterrupt) which is usually not what you want.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
0

See sys.exit. Notably:

This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

So you caught the exception and after the try-except-finally block is done, the script exits normally, not because you called exit(0). You can also change the script to exit with a non-zero exit code, then see that the script still exits with an exit code of 0.

Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34