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.
No. System. exit(0) doesn't return, and the finally block is not 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.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
A finally block always executes, regardless of whether an exception is thrown.
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 byfinally
clauses oftry
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With