Python 中的嵌套 try...except 语句

Python 中的嵌套 try...except 语句

try...except 语句在 Python 中用于捕获异常或运行一些容易出错的代码。如今,每种编程语言都具有此功能,但在 Python 中,它分别由这些词和 try...except 关键字表示。除了 try...except,另一个关键字,即 finally,也可以与它们一起使用。

for 循环一样,这些 trycatchfinally 语句也可以嵌套,在本文中,我们将讨论它。

Python 中的嵌套 try...except 语句

如上所述,我们可以像嵌套 for 循环一样嵌套这些语句。示例请参考以下代码。

a = {"a": 5, "b": 25, "c": 125}

try:
    print(a["d"])
except KeyError:
    try:
        print("a:", a["a"])
    except:
        print("No value exists for keys 'a' and 'd'")
    finally:
        print("Nested finally")
finally:
    print("Finally")

输出:

a: 5
Nested finally
Finally

正如我们所看到的,上面的程序首先用一些键值对初始化一个字典,然后尝试访问键 d 的值。由于不存在键值对,因此会引发 KeyError 异常并由 except 语句捕获。然后解释器在嵌套的 try 块下运行代码。由于键 a 存在一个值,它会打印到控制台,并执行嵌套的 finally 语句下的代码。最后,执行外部 finally 语句下的代码。

这意味着我们可以将 trycatchfinally 语句放在任何 trycatchfinally 语句下。让我们通过一个例子来理解这一点。我们将编写一些包含 trycatchfinally 语句的代码,所有这些语句下面也有 trycatchfinally 语句。

a = {
    "a": 5,
    "b": 25,
    "c": 125,
    "e": 625,
    "f": 3125,
}

try:
    try:
        print("d:", a["d"])
    except:
        print("a:", a["a"])
    finally:
        print("First nested finally")
except KeyError:
    try:
        print("b:", a["b"])
    except:
        print("No value exists for keys 'b' and 'd'")
    finally:
        print("Second nested finally")
finally:
    try:
        print("c:", a["c"])
    except:
        print("No value exists for key 'c'")
    finally:
        print("Third nested finally")

输出:

a: 5
First nested finally
c: 125
Third nested finally

正如我们所看到的,首先,外部的 try 块被执行。由于没有找到键 d 的值,嵌套的 except 语句下的代码将被执行,嵌套的 finally 将被执行。由于外层 try 块在执行过程中没有遇到任何异常,它的 except 块被跳过,并执行外层 finally 块下的代码。

我们甚至可以根据需要更进一步,创建 n 级嵌套的 trycatchfinally 语句。但是随着嵌套层数的增加,控制流或执行流变得有点复杂和难以管理。浏览 trycatchfinally 语句变得具有挑战性。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

相关文章 - Python Statement