Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 sumbyzero():     try:         10/0         print "It will never print"     except Exception:         sys.exit(0)         print "Printing after exit"     finally:         print "Finally will always print"  sumbyzero()  

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.

like image 860
Reuben Avatar asked Oct 10 '11 06:10

Reuben


People also ask

Will finally block executed if we give System Exit 0 in TRY block?

No. System. exit(0) doesn't return, and the finally block is not executed.

Why finally block is always executed?

A finally block is always get executed whether the exception has occurred or not. If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code. We cannot say the finally block is always executes because sometimes if any statement like System.

When finally block gets executed always?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

Does finally execute after exception?

A finally block always executes, regardless of whether an exception is thrown.


2 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.

like image 138
NPE Avatar answered Oct 05 '22 17:10

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...

like image 25
NilColor Avatar answered Oct 05 '22 18:10

NilColor