Why finally block is executing after calling sys.exit(0) in except block?

All sys.exit() does is raise an exception of type SystemExit.

From the documentation:

Exit from Python. 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.

If you run the following, you’ll see for yourself:

import sys
try:
  sys.exit(0)
except SystemExit as ex:
  print 'caught SystemExit:', ex

As an alternative, os._exit(n) with the status code will stop the process bypassing much of the cleanup, including finally blocks etc.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)