python - 相当于 try/except/finally 语句

标签 python python-3.x exception try-catch programming-languages

Python 简介

A try / except / finally statement, such as:

try:
    ...guarded clause...
except ...expression...:
    ...exception handler code...
finally:
    ...clean-up code...

is equivalent to the nested statement:

try:
    try:
        ...guarded clause...
    except ...expression...:
        ...exception handler code...
finally:
    ...clean-up code...
  1. 为什么它相当于嵌套表单?
  2. 是否可以写成与不带finally的形式等价?

    是否相当于

    try:
        ...guarded clause...
    except ...expression...:
        ...exception handler code...
        ...clean-up code...
    ...clean-up code...
    

谢谢。

最佳答案

  1. 因为这就是它的定义方式。因为以这种方式定义它是有用且标准的,并且因为没有其他有用的方法来定义它。
  2. 是的,但不是你这样做的方式。

    try:
        do_stuff()
    except OneProblem:
        handle_it()
    except DifferentProblem:
        handle_that()
    finally:
        cleanup()
    

    相当于

    try:
        try:
            do_stuff()
        except OneProblem:
            handle_it()
        except DifferentProblem:
            handle_that()
    except:
        # Clean up if an unhandled exception happened, then restore the exception.
        cleanup()
        raise
    # Also clean up if we're not propagating an exception.
    cleanup()
    

就清理而言,总是会发生并且不会发生两次,尽管异常链接和回溯之类的行为可能会有所不同。

关于python - 相当于 try/except/finally 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229716/

相关文章:

php - 深层链接无法正常工作

python - 在矩阵中找到最大值的索引(python)

python - YouTube分析

jquery - 显示 asp.net mvc ajax 请求错误的最佳方法是什么

python - 如何修复此 "TypeError: ' str' 对象不可调用“错误?

python - 使用 Altair 直接标记线图

python - Raspberry Pi 中的硬币计数器 (RPi-GPIO)

python - Pandas 数据帧 : Split a column into multiple columns

android - Android Build在 ':app:dexDebug'失败,出现异常(库和应用程序项目)

c#-4.0 - 根据非并行任务实现同步方法的模式(翻译/展开聚合异常)