相关疑难解决方法(0)

为什么我们需要Python中的"finally"子句?

我不知道为什么我们需要finallytry...except...finally声明中.在我看来,这个代码块

try:
    run_code1()
except TypeError:
    run_code2()
other_code()
Run Code Online (Sandbox Code Playgroud)

与使用finally以下内容相同:

try:
    run_code1()
except TypeError:
    run_code2()
finally:
    other_code()
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

python exception-handling try-finally

264
推荐指数
9
解决办法
11万
查看次数

其他目的,最后是异常处理

elsefinally异常处理部分多余的?例如,以下两个代码段之间有什么区别吗?

try:
    foo = open("foo.txt")
except IOError:
    print("error")
else:
    print(foo.read())
finally:
    print("finished")
Run Code Online (Sandbox Code Playgroud)

try:
    foo = open("foo.txt")
    print(foo.read())
except IOError:
    print("error")
print("finished")
Run Code Online (Sandbox Code Playgroud)

更一般地说,不能将内容else总是移入try,而不能将内容finally移到try/catch块之外?如果是这样,是什么目的elsefinally?它只是为了增强可读性吗?

python

63
推荐指数
4
解决办法
2万
查看次数

重新引发异常不适用于“finally”子句

当我放入finally子句时,raise语句 inexcept不起作用。

所以except块不会产生Exception.

我错过了什么?如果我想重新提高Exceptionafterfinally子句返回值,我需要做什么?

def test():
    res = 1
    try:
            raise Exception
            res = 2
    except:
            print('ha fallado')
            raise

    finally:
            return res
test()
Run Code Online (Sandbox Code Playgroud)

解决方案

def test():
    res = 1
    try:
            raise Exception
            res = 2
    except:
            print('ha fallado')
            raise

    finally:
            # ... finally code that need to exec
            pass

    return res

print(test())
Run Code Online (Sandbox Code Playgroud)

这样,如果发生异常,except 块会处理该异常,然后引发它。

如果没有发生异常,则返回该值。

感谢所有的答案!这么快 :)

python exception

2
推荐指数
1
解决办法
753
查看次数