<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Python 使用`try`,`except`和`finally`語句的異常處理 > 原文: [https://www.programiz.com/python-programming/exception-handling](https://www.programiz.com/python-programming/exception-handling) #### 在本教程中,您將在示例的幫助下使用`try`,`except`和`finally`語句學習如何在 Python 程序中處理異常。 ## Python 異常 Python 有許多[內置異常](/python-programming/exceptions),這些異常在您的程序遇到錯誤(程序中的某些地方出錯)時引發。 當發生這些異常時,Python 解釋器將停止當前進程并將其傳遞給調用進程,直到對其進行處理。 如果不處理,程序將崩潰。 例如,讓我們考慮一個程序,其中有一個[函數](/python-programming/function) `A`,該函數調用函數`B`,該函數又調用函數`C`。 如果異常在函數`C`中發生,但未在`C`中處理,則該異常傳遞給`B`,然后傳遞給`A`。 如果從未處理過,則會顯示一條錯誤消息,并且我們的程序突然突然中止。 * * * ## 在 Python 中捕捉異常 在 Python 中,可以使用`try`語句處理異常。 可能引發異常的關鍵操作放在`try`子句中。 處理異常的代碼寫在`except`子句中。 因此,一旦捕獲到異常,我們可以選擇要執行的操作。 這是一個簡單的例子。 ```py # import module sys to get the type of exception import sys randomList = ['a', 0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except: print("Oops!", sys.exc_info()[0], "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r) ``` **輸出** ```py The entry is a Oops! <class 'ValueError'> occurred. Next entry. The entry is 0 Oops! <class 'ZeroDivisionError'> occured. Next entry. The entry is 2 The reciprocal of 2 is 0.5 ``` 在此程序中,我們遍歷`randomList`列表的值。 如前所述,可能導致異常的部分位于`try`塊內。 如果沒有異常,則跳過`except`塊,繼續正常流程(最后一個值)。 但是,如果發生任何異常,它將被`except`塊(第一個和第二個值)捕獲。 在這里,我們使用`sys`模塊內的`exc_info()`函數打印異常的名稱。 我們可以看到`a`導致`ValueError`和`0`導致`ZeroDivisionError`。 由于 Python 中的每個異常都繼承自基本`Exception`類,因此我們還可以通過以下方式執行上述任務: ```py # import module sys to get the type of exception import sys randomList = ['a', 0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except Exception as e: print("Oops!", e.__class__, "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r) ``` 該程序具有與上述程序相同的輸出。 * * * ## 捕獲 Python 中的特定異常 在上面的示例中,我們沒有在`except`子句中提及任何特定的異常。 這不是一個好的編程習慣,因為它將捕獲所有異常并以相同的方式處理每種情況。 我們可以指定`except`子句應捕獲的異常。 一個`try`子句可以具有任意數量的`except`子句來處理不同的異常,但是,如果發生異常,則僅執行一個子句。 我們可以使用值的元組在`except`子句中指定多個異常。 這是示例偽代碼。 ```py try: # do something pass except ValueError: # handle ValueError exception pass except (TypeError, ZeroDivisionError): # handle multiple exceptions # TypeError and ZeroDivisionError pass except: # handle all other exceptions pass ``` * * * ## 在 Python 中引發異常 在 Python 編程中,在運行時發生錯誤時會引發異常。 我們還可以使用`raise`關鍵字手動引發異常。 我們可以選擇將值傳遞給異常,以闡明引發該異常的原因。 ```py >>> raise KeyboardInterrupt Traceback (most recent call last): ... KeyboardInterrupt >>> raise MemoryError("This is an argument") Traceback (most recent call last): ... MemoryError: This is an argument >>> try: ... a = int(input("Enter a positive integer: ")) ... if a <= 0: ... raise ValueError("That is not a positive number!") ... except ValueError as ve: ... print(ve) ... Enter a positive integer: -2 That is not a positive number! ``` * * * ## Python `try-else`子句 在某些情況下,如果`try`中的代碼塊運行無誤,則可能要運行某個代碼塊。 對于這些情況,可以在`try`語句中使用可選的`else`關鍵字。 **注意**:`else`子句不會處理`else`子句中的異常。 讓我們看一個例子: ```py # program to print the reciprocal of even numbers try: num = int(input("Enter a number: ")) assert num % 2 == 0 except: print("Not an even number!") else: reciprocal = 1/num print(reciprocal) ``` **輸出**: 如果我們傳遞一個奇數: ```py Enter a number: 1 Not an even number! ``` 如果我們傳遞一個偶數,則將計算并顯示倒數。 ```py Enter a number: 4 0.25 ``` 但是,如果傳遞 0,則會得到`ZeroDivisionError`,因為`else`內部的代碼塊未由前面的`except`處理。 ```py Enter a number: 0 Traceback (most recent call last): File "<string>", line 7, in <module> reciprocal = 1/num ZeroDivisionError: division by zero ``` * * * ## Python `try-finally` Python 中的`try`語句可以具有可選的`finally`子句。 該子句無論如何執行,通常用于釋放外部資源。 例如,我們可能通過網絡或使用文件或圖形用戶界面(GUI)連接到遠程數據中心。 在所有這些情況下,無論程序是否成功運行,我們都必須在程序停止之前清理資源。 這些操作(關閉文件,GUI 或與網絡斷開連接)在`finally`子句中執行,以確保執行。 這是[文件操作](/python-programming/file-operation)的示例來說明這一點。 ```py try: f = open("test.txt",encoding = 'utf-8') # perform file operations finally: f.close() ``` 這種類型的構造可確保即使在程序執行期間發生異常,也可以關閉文件。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看