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

Question:

I’m new to Python. I just want to know why the finally block is executing after calling sys.exit(0) in the except block?

Code:

import sys

def divide_by_zero():
    try:
        10/0
        print "It will never print"
    except Exception:
        sys.exit(0)
        print "Printing after exit"
    finally:
        print "Finally will always print"

divide_by_zero() 

Btw., I was just trying to do the same thing as in Java, where the finally block is not executed when System.exit(0) is in the catch block.

Asked By: Reuben

||

Answers:

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.

Answered By: NPE

You should use os._exit(0).

About your example:

A finally clause is always executed before leaving the try statement,
whether an exception has occurred or not.

This is from Error and Exceptions part of Python docs. So – your finally block will always be executed in example you show unless you will use os._exit(0). But you should use it wisely…

Answered By: NilColor
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.