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