相关疑难解决方法(0)

使用Return语句的奇怪的Try-Except-Else-Finally行为

这是一些表现特殊的代码.这是我编写的行为的简化版本.这仍然会表现出奇怪的行为,并且我对于为什么会这样做有一些具体的问题.

我在Windows 7上使用Python 2.6.6.

def demo1():
    try:
        raise RuntimeError,"To Force Issue"
    except:
        return 1
    else:
        return 2
    finally:
        return 3

def demo2():
    try:
        try:
            raise RuntimeError,"To Force Issue"
        except:
            return 1
        else:
            return 2
        finally:
            return 3
    except:
        print 4
    else:
        print 5
    finally:
        print 6
Run Code Online (Sandbox Code Playgroud)

结果:

>>> print demo1()
3
>>> print demo2()
6
3
Run Code Online (Sandbox Code Playgroud)
  • 为什么demo 1返回3而不是1?
  • 为什么演示两次打印6而不是打印6 w/4或5?

python try-except

77
推荐指数
3
解决办法
3万
查看次数

标签 统计

python ×1

try-except ×1