当我使用Ctrl+;终止Python脚本时,内部会发生什么;C
这些天我正在深入学习Python的异常处理特性。我遇到异常SystemExit。在阅读本文时,我想到了这样一个问题:当我按Ctrl+c终止Python脚本时,会发生什么 让我们以以下示例代码为例:当我使用Ctrl+;终止Python脚本时,内部会发生什么;C,python,exception-handling,Python,Exception Handling,这些天我正在深入学习Python的异常处理特性。我遇到异常SystemExit。在阅读本文时,我想到了这样一个问题:当我按Ctrl+c终止Python脚本时,会发生什么 让我们以以下示例代码为例: def func1(a,b): print "func1: "+str(a/b) #some more functions def func2(a,b): print "func2: "+str(a/b) #some more functions if __name
def func1(a,b):
print "func1: "+str(a/b)
#some more functions
def func2(a,b):
print "func2: "+str(a/b)
#some more functions
if __name__=="__main__":
import random
count=0
for i in range(1000000):
count=count+1
print "count: "+str(count)
try:
func1(random.randint(-2,3),random.randint(-2,3))
except KeyboardInterrupt:
raise
except:
print "error in func1"
try:
func2(random.randint(-2,3),random.randint(-2,3))
except KeyboardInterrupt:
raise
except:
print "error in func2"
print "\n"
在这个示例代码中,我捕获了
键盘中断
,因此我可以通过按Ctrl+c停止脚本。我是否也应该捕获SystemExit
,以使此代码更加成熟?如果是,为什么?实际上,这个问题是我主要问题的来源,出现在标题上。所以不要认为我在一个帖子里问了两个不同的问题。 您通常不需要捕获SystemExit
,因为这是使功能正常工作的原因:
系统退出([arg])
退出Python。这是通过引发SystemExit
异常来实现的,因此执行try
语句的finally
子句指定的清理操作,并且可以在外部级别拦截退出尝试
例如:
try:
exit()
except SystemExit:
print "caught"
因此,您通常不希望首先捕获所有异常(通过使用空的
except:
子句)。最好的方法通常是使异常处理程序尽可能具体。否则,调试应用程序会异常困难,因为它要么完全隐藏错误,要么至少很难诊断详细信息。函数可以引发的唯一异常是零分区错误
,因此您应该只捕获该错误:
import random
if __name__ == "__main__":
for count in range(1000000):
print "count:", count
try:
func1(random.randint(-2, 3),random.randint(-2, 3))
except ZeroDivisionError:
print "error in func1"
try:
func2(random.randint(-2, 3),random.randint(-2, 3))
except ZeroDivisionError:
print "error in func2"
print "\n"
你的标题与你的问题的主体有所不同
SIGINT
,并从中引发了键盘中断
异常操作,除了:
相反,你想要
if __name__=="__main__":
try:
import random
count=0
for i in range(1000000):
count=count+1
print "count: "+str(count)
try:
func1(random.randint(-2,3),random.randint(-2,3))
except Exception, e:
print "error in func1", e # or something...
try:
func2(random.randint(-2,3),random.randint(-2,3))
except Exception, e:
print "error in func2", e # or something...
print "\n"
except Exception:
raise # any other "normal" exception.
except: # Here it is ok, as you handle most exceptions above.
pass
异常
。那些具有内在含义且通常不应被捕获(全球层面除外)的内容不会被捕获
这些是
KeyboardInterrupt
,SystemExit
和GeneratorExit
,如果您不确定要调用的代码会抛出哪些异常来指示错误,那么您应该(按优先顺序):
KeyboardInterrupt
和SystemExit
都不是Exception
的子类,但用于指示错误的所有标准Python异常都是。我不确定您的问题是什么。您已经知道,KeyboardInterrupt
是在执行CTRL+C
时引发的异常,那么您想问什么?只有SystemExit
的问题可以简单地回答为“否”。谢谢,确切的问题是我的标题,正文部分是我问题的来源。这只是一个示例代码,这就是我编写#更多函数的原因。因此,我们可能会得到更多的错误,然后您应该找出可以在那里引发哪些异常,并且只捕获这些异常。回答你的问题;成熟的代码只会捕获那些可能发生的异常,并且只会在程序可以安全地从该状态恢复时捕获它们。我的标题是问题,正文是我问题的来源