【问题标题】:nested try except in python嵌套尝试除了在python中
【发布时间】:2015-02-22 13:00:30
【问题描述】:
Try: 
     #some statement 
    Try: 
         #some statement 
    Except: 
         #statement1 
        Raise exception()
       #statement2 
Except: #some statement

我可以像上面的python代码那样传递控件吗?内部的except是否会将控件传递给外部的except,#statement2会被执行吗?

【问题讨论】:

  • 附注:它们没有大写字母。关于你的问题:你为什么不测试它?

标签: python nested try-catch except


【解决方案1】:

此代码将回答您的问题:

#!/usr/bin/env python
import sys
try:
    try:
        raise Exception("first exception")
    except Exception as e:
        print e.message
        raise Exception("second exception")
        print "second statement" # never printed - 'dead code'
except Exception as e:
    print e.message

两个except 块都被执行,但引发第二个异常后的语句没有。

通常您应该知道,一旦引发异常,除非它被与此异常或其任何超类相关的 except 块捕获,否则不会执行任何操作。

【讨论】:

  • 问题中提到的#statement2 此处未提及
  • @keyser 添加了一个更相关的示例,感谢您的评论。
猜你喜欢
  • 2013-04-25
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2014-03-29
相关资源
最近更新 更多