<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 自定義異常 > 原文: [https://www.programiz.com/python-programming/user-defined-exception](https://www.programiz.com/python-programming/user-defined-exception) #### 在本教程中,您將借助示例學習如何根據需要定義自定義異常。 Python 有許多[內置異常](/python-programming/exceptions),它們會在程序出現問題時強制您的程序輸出錯誤。 但是,有時您可能需要創建自己的自定義異常來滿足您的目的。 * * * ## 創建自定義異常 在 Python 中,用戶可以通過創建新類來定義自定義異常。 必須從內置的`Exception`類直接或間接派生此異常類。 大多數內置異常也是從此類派生的。 ```py >>> class CustomError(Exception): ... pass ... >>> raise CustomError Traceback (most recent call last): ... __main__.CustomError >>> raise CustomError("An error occurred") Traceback (most recent call last): ... __main__.CustomError: An error occurred ``` 在這里,我們創建了一個名為`CustomError`的用戶定義異常,該異常繼承自`Exception`類。 與其他異常一樣,可以使用`raise`語句以及可選的錯誤消息來引發此新異常。 當我們開發大型 Python 程序時,最好將程序引發的所有用戶定義的異常放在單獨的文件中。 許多標準模塊可以做到這一點。 它們分別將其異常定義為`exceptions.py`或`errors.py`(通常但并非總是如此)。 用戶定義的異常類可以實現普通類可以做的所有事情,但是我們通常使它們簡單明了。 大多數實現都聲明一個自定義基類,并從該基類派生其他異常類。 在下面的示例中,將使該概念更清晰。 * * * ## 示例:Python 中的用戶定義異常 在此示例中,我們將說明如何在程序中使用用戶定義的異常來引發和捕獲錯誤。 該程序將要求用戶輸入一個數字,直到他們正確猜出一個存儲的數字為止。 為了幫助他們弄清楚,他們的猜測是大于還是小于所存儲的數字。 ```py # define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class ValueTooSmallError(Error): """Raised when the input value is too small""" pass class ValueTooLargeError(Error): """Raised when the input value is too large""" pass # you need to guess this number number = 10 # user guesses a number until he/she gets it right while True: try: i_num = int(input("Enter a number: ")) if i_num < number: raise ValueTooSmallError elif i_num > number: raise ValueTooLargeError break except ValueTooSmallError: print("This value is too small, try again!") print() except ValueTooLargeError: print("This value is too large, try again!") print() print("Congratulations! You guessed it correctly.") ``` 這是該程序的示例運行。 ```py Enter a number: 12 This value is too large, try again! Enter a number: 0 This value is too small, try again! Enter a number: 8 This value is too small, try again! Enter a number: 10 Congratulations! You guessed it correctly. ``` 我們定義了一個名為`Error`的基類。 我們程序實際引發的另外兩個異常(`ValueTooSmallError`和`ValueTooLargeError`)是從此類派生的。 這是在 Python 編程中定義用戶定義的異常的標準方法,但不僅限于此。 * * * ## 自定義異常類 我們可以進一步自定義此類,以根據需要接受其他參數。 要了解有關自定義`Exception`類的信息,您需要具有面向對象編程的基礎知識。 訪問 [Python 面向對象編程](/python-programming/object-oriented-programming),開始學習 Python 中的面向對象編程。 讓我們看一個例子: ```py class SalaryNotInRangeError(Exception): """Exception raised for errors in the input salary. Attributes: salary -- input salary which caused the error message -- explanation of the error """ def __init__(self, salary, message="Salary is not in (5000, 15000) range"): self.salary = salary self.message = message super().__init__(self.message) salary = int(input("Enter salary amount: ")) if not 5000 < salary < 15000: raise SalaryNotInRangeError(salary) ``` **輸出** ```py Enter salary amount: 2000 Traceback (most recent call last): File "<string>", line 17, in <module> raise SalaryNotInRangeError(salary) __main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range ``` 在這里,我們覆蓋了`Exception`類的構造器,以接受我們自己的自定義參數`salary`和`message`。 然后,使用`super()`和`self.message`參數手動調用父`Exception`類的構造器。 自定義`self.salary`屬性定義為以后使用。 然后,當引發`SalaryNotInRangeError`時,將使用`Exception`類的繼承的`__str__`方法顯示相應的消息。 我們也可以通過覆蓋`__str__`方法本身來定制它。 ```py class SalaryNotInRangeError(Exception): """Exception raised for errors in the input salary. Attributes: salary -- input salary which caused the error message -- explanation of the error """ def __init__(self, salary, message="Salary is not in (5000, 15000) range"): self.salary = salary self.message = message super().__init__(self.message) def __str__(self): return f'{self.salary} -> {self.message}' salary = int(input("Enter salary amount: ")) if not 5000 < salary < 15000: raise SalaryNotInRangeError(salary) ``` **輸出**: ```py Enter salary amount: 2000 Traceback (most recent call last): File "/home/bsoyuj/Desktop/Untitled-1.py", line 20, in <module> raise SalaryNotInRangeError(salary) __main__.SalaryNotInRangeError: 2000 -> Salary is not in (5000, 15000) range ``` * * * 要了解有關如何使用 Python 處理異常的更多信息,請訪問 [Python 異常處理](/python-programming/exception-handling)。
                  <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>

                              哎呀哎呀视频在线观看