Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

คลาสพื้นฐานของข้อยกเว้นใน Python


ทุกข้อยกเว้นใน Python สืบทอดมาจากคลาส BaseException ข้อยกเว้นที่ผู้ใช้สร้าง (user-defined) ต้องสืบทอดจากคลาส Exception ไม่ใช่ BaseException โดยตรง

ลำดับชั้นของข้อยกเว้น (Exception Hierarchy)

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

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 Occurred: The age must be greater than 18 years