小编LSZ*_*LSZ的帖子

为什么函数返回抑制引发的异常?

检查以下有关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
Run Code Online (Sandbox Code Playgroud)

然后运行myfunc()将输出而不会弹出任何异常

no matter exception occurs or not
Run Code Online (Sandbox Code Playgroud)

但是如果注释中的finally子句中的'return a'代码,输出将捕获未处理的myException2,

no matter exception occurs or not
---------------------------------------------------------------------------
myException2                              Traceback (most recent call last)
<ipython-input-140-29dfc9311b33> in <module>()
----> 1 …
Run Code Online (Sandbox Code Playgroud)

python exception

3
推荐指数
1
解决办法
96
查看次数

标签 统计

exception ×1

python ×1