Python 異常基類


像其他高階語言一樣,Python 中也有一些異常。當出現問題時,它會引發異常。存在不同型別的異常,例如 **ZeroDivisionError、AssertionError** 等。所有異常類都派生自 BaseException 類。

程式碼可以執行內建異常,我們也可以在程式碼中引發這些異常。使用者可以從 **Exception** 類或 **Exception** 類的任何其他子類派生自己的異常。

BaseException 是所有其他異常的基類。使用者定義的類不能直接從此類派生,要派生使用者定義的類,我們需要使用 Exception 類。

Python 異常層次結構如下所示。

  • BaseException
  • Exception
    • ArithmeticError
      • FloatingPointError
      • OverflowError
      • ZeroDivisionError
    • AssertionError
    • AttributeError
    • BufferError
    • EOFError
    • ImportError
      • ModuleNotFoundError
    • LookupError
      • IndexError
      • KeyError
    • MemoryError
    • NameError
      • UnboundLocalError
    • OSError
      • BlockingIOError
      • ChildProcessError
      • ConnectionError
        • BrokenPipeError
        • ConnectionAbortedError
        • ConnectionRefusedError
        • ConnectionResetError
    • FileExistsError
    • FileNotFoundError
    • InterruptedError
    • IsADirectoryError
    • NotADirectoryError
    • PermissionError
    • ProcessLookupError
    • TimeoutError
  • ReferenceError
  • RuntimeError
    • NotImplementedError
    • RecursionError
  • StopIteration
  • StopAsyncIteration
  • SyntaxError
    • IndentationError
      • TabError
  • SystemError
  • TypeError
  • ValueError
    • UnicodeError
      • UnicodeDecodeError
      • UnicodeEncodeError
      • UnicodeTranslateError
  • Warning
    • BytesWarning
    • DeprecationWarning
    • FutureWarning
    • ImportWarning
    • PendingDeprecationWarning
    • ResourceWarning
    • RuntimeWarning
    • SyntaxWarning
    • UnicodeWarning
    • UserWarning
  • GeneratorExit
  • KeyboardInterrupt
  • SystemExit

問題 - 在此問題中,有一個員工類。條件是,員工的年齡必須大於 18 歲。

我們應該建立一個使用者定義的異常類,它是 Exception 類的子類。

示例程式碼

 即時演示

class LowAgeError(Exception):
   def __init__(self):
      pass

   def __str__(self):
      return 'The age must be greater than 18 years'

class Employee:
   def __init__(self, name, age):
      self.name = name
      if age < 18:
      raise LowAgeError
      else:
      self.age = age

   def display(self):
      print('The name of the employee: ' + self.name + ', Age: ' + str(self.age) +' Years')

      try:
      e1 = Employee('Subhas', 25)
      e1.display()

      e2 = Employee('Anupam', 12)
      e1.display()
except LowAgeError as e:
   print('Error Occurred: ' + str(e))

輸出

The name of the employee: Subhas, Age: 25 Years
Error OccurredThe age must be greater than 18 years

更新於: 2020-06-25

5K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.