Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/7709411/why-finally-block-is-executing-after-calling-sys-exit0-in-except-block

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() will stop the process bypassing much of the cleanup, including finally blocks etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...