<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>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Python 異常 > 原文: [http://zetcode.com/lang/python/exceptions/](http://zetcode.com/lang/python/exceptions/) 在 Python 教程的這一部分中,我們討論 Python 中的異常。 執行期間檢測到的錯誤稱為異常。 在執行應用期間,許多事情可能出錯。 磁盤可能已滿,我們無法保存文件。 互聯網連接可能斷開,我們的應用嘗試連接到站點。 所有這些都可能導致我們的應用崩潰。 為防止這種情況,我們必須應對可能發生的所有可能的錯誤。 為此,我們可以使用異常處理。 ## 在 Python 中捕捉異常 在 Python 中,我們具有以下語法來處理異常: ```py try: # do something except ValueError: # handle ValueError exception except (IndexError, ZeroDivisionError): # handle multiple exceptions # IndexError and ZeroDivisionError except: # handle all other exceptions finally: # cleanup resources ``` 我們期望發生異常的代碼寫在`try`塊中。 `except`關鍵字捕獲程序中指定的或剩余的異常。 始終執行可選的`finally`塊; 它用于清除資源,例如打開的文件或數據庫連接。 ## `ZeroDivisionError` 除以零是不可能的。 如果我們嘗試執行此操作,則會引發`ZeroDivisionError`并中斷腳本。 > **注意**:以下示例演示了異常在 Python 中的工作方式。 確保除數不為零而不是捕獲`ZeroDivisionError`更直接。 `zero_division.py` ```py #!/usr/bin/env python # zero_division.py def input_numbers(): a = float(input("Enter first number:")) b = float(input("Enter second number:")) return a, b x, y = input_numbers() print(f"{x} / {y} is {x/y}") ``` 在此腳本中,我們從控制臺獲得兩個數字。 我們將這兩個數相除。 如果第二個數字為零,則會出現異常。 ```py Enter first number:3 Enter second number:0 Traceback (most recent call last): File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 14, in <module> print(f"{x} / {y} is {x/y}") ZeroDivisionError: float division by zero ``` 我們可以通過兩種方式處理此問題。 `zero_division2.py` ```py #!/usr/bin/env python # zero_division2.py def input_numbers(): a = float(input("Enter first number:")) b = float(input("Enter second number:")) return a, b x, y = input_numbers() while True: if y != 0: print(f"{x} / {y} is {x/y}") break else: print("Cannot divide by zero") x, y = input_numbers() ``` 首先,我們僅檢查`y`的值不為零。 如果`y`值為零,我們將打印警告消息并再次重復輸入周期。 這樣我們就可以處理錯誤,并且腳本不會中斷。 ```py $ ./zero_division2.py Enter first number:4 Enter second number:0 Cannot divide by zero Enter first number:5 Enter second number:0 Cannot divide by zero Enter first number:5 Enter second number:6 5.0 / 6.0 is 0.8333333333333334 ``` 另一種方法是使用異常。 `zero_division3.py` ```py #!/usr/bin/env python # zerodivision3.py def input_numbers(): a = float(input("Enter first number:")) b = float(input("Enter second number:")) return a, b x, y = input_numbers() try: print(f"{x} / {y} is {x/y}") except ZeroDivisionError: print("Cannot divide by zero") x, y = input_numbers() ``` 我們將代碼放置在`try`關鍵字之后我們期望發生異常的位置。 如果引發了`except`關鍵字,則捕獲該異常。 異常類型在`except`關鍵字之后指定。 ```py except ValueError: pass except (IOError, OSError): pass ``` 要處理更多的異常,我們可以使用除關鍵字之外的更多異常,也可以將異常名稱放在元組中。 ## `ValueError` 當內置操作或函數接收到類型正確但值不合適的自變量時,會引發`ValueError`,并且無法通過更精確的異常描述這種情況。 `value_error.py` ```py #!/usr/bin/env python # value_error.py def read_age(): age = int(input("Enter your age: ")) if age < 0 or age > 130: raise ValueError("Invalid age") return age try: val = read_age() print(f"Your age is {val}") except ValueError as e: print(e) ``` 在該示例中,我們有一個讀取年齡作為用戶輸入的函數。 當用戶提供不正確的值時,我們將引發`ValueError`異常。 ```py if age < 0 or age > 130: raise ValueError("Invalid age") return age ``` 負年齡是沒有道理的,在現代沒有記錄到年齡超過 130 歲的人。 ## Python 多個異常 可以在一個`except`子句中捕獲多個異常。 `multiple_exceptions.py` ```py #!/usr/bin/env python # multiple_exceptions.py import os try: os.mkdir('newdir') print('directory created') raise RuntimeError("Runtime error occurred") except (FileExistsError, RuntimeError) as e: print(e) ``` 該代碼示例在一個`except`語句中捕獲了兩個異常:`FileExistsError`和`RuntimeError`。 ```py os.mkdir('newdir') ``` 使用`os.mkdir()`方法創建一個新目錄。 如果目錄已經存在,則觸發`FileExistsError`。 ```py raise RuntimeError("Runtime error occurred") ``` 我們使用`raise`關鍵字手動引發運行時異常。 ## Python 異常參數 異常可以具有關聯的值,該值指示錯誤的詳細原因。 該值放在`as`關鍵字之后。 `exception_as.py` ```py #!/usr/bin/env python # exception_argument.py try: a = (1, 2, 3, 4) print(a[5]) except IndexError as e: print(e) print("Class:", e.__class__) ``` 從異常對象中,我們可以獲取錯誤消息或類名。 ```py $ ./exception_as.py tuple index out of range Class: <class 'IndexError'> ``` ## Python 異常層次結構 異常是按層次結構組織的,它們是所有異常的父級`Exception`。 `interrupt.py` ```py #!/usr/bin/env python # interrupt.py try: while True: pass except KeyboardInterrupt: print("Program interrupted") ``` 腳本開始并不斷循環。 如果按 `Ctrl + C` ,我們將中斷循環。 在這里,我們捕獲了`KeyboardInterrupt`異常。 ```py Exception BaseException KeyboardInterrupt ``` 這是`KeyboardInterrupt`異常的層次結構。 `interrupt2.py` ```py #!/usr/bin/env python # interrupt2.py try: while True: pass except BaseException: print("Program interrupted") ``` 這個例子也可以。 `BaseException`也捕獲鍵盤中斷; 除其他異常。 但是,這不是一個好習慣。 我們應該在`except`子句中捕獲特定的異常。 ## Python 用戶定義的異常 如果需要,我們可以創建自己的異常。 我們通過定義一個新的異常類來做到這一點。 `user_defined.py` ```py #!/usr/bin/env python # user_defined.py class BFoundEx(Exception): def __init__(self, value): self.par = value def __str__(self): return f"BFoundEx: b character found at position {self.par}" string = "There are beautiful trees in the forest." pos = 0 for i in string: try: if i == 'b': raise BFoundEx(pos) pos = pos + 1 except BFoundEx as e: print(e) ``` 在我們的代碼示例中,我們創建了一個新的異常。 異常是從基類`Exception`派生的。 如果在字符串中發現字母`b`的任何出現,我們將`raise`作為異常。 ```py $ ./user_defined.py 'BFoundEx: b character found at position 10' ``` ## 清理 有一個`finally`關鍵字,始終會執行。 不管是否引發異常。 它通常用于清理程序中的資源。 `cleanup.py` ```py #!/usr/bin/env python # cleanup.py f = None try: f = open('data.txt', 'r') contents = f.readlines() for line in contents: print(line.rstrip()) except IOError: print('Error opening file') finally: if f: f.close() ``` 在我們的示例中,我們嘗試打開一個文件。 如果我們無法打開文件,則會彈出`IOError`。 如果我們打開文件,我們想關閉文件處理器。 為此,我們使用`finally`關鍵字。 在`finally`塊中,我們檢查文件是否已打開。 如果打開了,我們將其關閉。 當我們使用數據庫時,這是一種常見的編程結構。 在那里,我們類似地清理打開的數據庫連接。 ## 棧跟蹤 棧跟蹤顯示了引發未捕獲的異常時的調用棧(至此為止已調用的函數棧)。 Python `traceback`模塊提供了一個標準接口,用于提取,格式化和打印 Python 程序的棧跟蹤。 它精確地模仿了 Python 解釋器在打印棧跟蹤時的行為。 `stacktrace_ex.py` ```py #!/usr/bin/env python # stacktrace_ex.py import traceback def myfun(): def myfun2(): try: 3 / 0 except ZeroDivisionError as e: print(e) print("Class:", e.__class__) for line in traceback.format_stack(): print(line.strip()) myfun2() def test(): myfun() test() ``` 在示例中,我們在嵌套的`myfun2`函數中將除以零的異常。 ```py for line in traceback.format_stack(): ``` `format_stack()`從當前棧幀中提取原始回溯并將其格式化為元組列表。 我們使用`for`循環遍歷元組列表。 ```py $ ./stacktrace_ex.py division by zero Class: <class 'ZeroDivisionError'> File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 30, in <module> test() File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 27, in test myfun() File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 23, in myfun myfun2() File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 20, in myfun2 for line in traceback.format_stack(): ``` 在程序中,我們可以看到調用棧-導致錯誤的被調用函數的順序。 在本章中,我們介紹了 Python 中的異常。
                  <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>

                              哎呀哎呀视频在线观看