2014-04-08 40 views
2

检查有关的异常处理下面的代码在python为什么在函数中返回抑制引发的异常?

class myException(Exception): 
    def __str__(self): 
     return 'this is my exception' 
class myException2(Exception): 
    def __str__(self): 
     return 'this is my exception 2' 
def myfunc(): 
    try: 
     raise myException2 
     print('after exception') 
    except myException: 
     a = 'exception occur' 
     print(a) 
    else: 
     a = 'exception doesn\'t occur' 
     print(a) 
    finally: 
     a = 'no matter exception occurs or not' 
     print(a) 
     return a 

然后乳宁MYFUNC()将没有任何异常输出弹出

no matter exception occurs or not 

但如果在最后条款“返回”代码评论,输出将捕获未处理的myException2,

no matter exception occurs or not 
--------------------------------------------------------------------------- 
myException2        Traceback (most recent call last) 
<ipython-input-140-29dfc9311b33> in <module>() 
----> 1 myfunc() 

<ipython-input-139-ba35768198b8> in myfunc() 
     1 def myfunc(): 
     2  try: 
----> 3   raise myException2 
     4   print('after exception') 
     5  except myException: 

myException2: this is my exception 2 

为什么返回码对于采集卡非常重要异常?

回答

4

直接从python docs

如果最后存在时,它指定一个“清除”处理程序。执行try 子句,包括任何except和else子句。如果任何一个条款中发生异常并且未处理, 异常将暂时保存。 finally子句被执行。如果 有一个保存的异常,它会在finally 子句的末尾重新生成。 如果最后条款引发了另一个异常或执行 退货或break语句,保存异常被丢弃:

这是有道理的,因为打印这个错误在最后发言结束时会发生。您可以提前退出该语句,以便不应该执行打印。

+0

非常感谢。 – Lansiz

相关问题