User-Defined Exception trong Python

Đây là bài 38/54 bài của series môn học Ngôn ngữ lập trình Python

Chúng ta đã cùng tìm hiểu về Exception ở bài Lỗi (error) và ngoại lệ (exception) trong Python. Sau đó, cách xử lý Exception cũng đã được giới thiệu ở bài Cách xử lý ngoại lệ (exception) trong Python. Python đã cung cấp rất nhiều Exception được xây dựng sẵn để giúp chúng ta bắt các Exception. Nhưng đôi khi, chúng ta cũng cần tạo ra những Exception riêng nhằm phục vụ mục đích riêng của chúng ta. Các Exception đó gọi là Exception do người dùng định nghĩa (User-Defined Exception).

1. Tạo một User-Defined Exception trong Python

Trong Python, chúng ta có thể tạo một lớp User-Defined Exception mới bằng cách kế thừa lớp Exception.

# class MyError inherits from class Exception
class MyError(Exception):
  # constructor method
  def __init__(self, message):
    self.message = message

  # __str__ display function
  def __str__(self):
    return self.message

try:
  # throw MyError Exception
  raise MyError("User-Defined Exception.")
except MyError as error:
  print('A New Exception occured:', error.message)
Kết quả
A New Exception occured: User-Defined Exception.

Khi một User-Defined Exception kế thừa lớp Exception thì nó có thể định nghĩa lại một số phương thức của Exception mà nó kế thừa được.

class MonthWrongValueError(Exception):
  """Exception raised for errors in the input month.

  Attributes:
      month -- input month which caused the error
      message -- explanation of the error
  """
  def __init__(self, month, message="Month is not in (1, 12) range"):
    self.month = month
    self.message = message
    super().__init__(self.message)
  
  def __str__(self):
    return f'{self.month} -> {self.message}'

month_input = int(input("Enter month: "))
if not 1 <= month_input <= 12:
  raise MonthWrongValueError(month_input)
else:
  print("month: ", month_input)
Kết quả 1
Enter month: 10
month:  10
Kết quả 2
Enter month: 25
Traceback (most recent call last):
  File "c:\python-examples\main.py", line 18, in <module>
    raise MonthWrongValueError(month_input)
__main__.MonthWrongValueError: 25 -> Month is not in (1, 12) range

Trong ví dụ trên, lớp MonthWrongValueError kế thừa lớp Exception. Lớp MonthWrongValueError đã định nghĩa lại hàm __init__()__str__() của lớp Exception để phù hợp với yêu cầu xuất thông báo lỗi của nó.

2. Kế thừa một User-Defined Exception trong Python

Một lớp User-Defined Exception có thể được kế thừa bởi các lớp User-Defined Exception khác mà chúng ta tự định nghĩa.

# class MyError inherits from class Exception
class MyError(Exception):
  # constructor method
  def __init__(self, message):
    self.message = message

  # __str__ display function
  def __str__(self):
    return self.message

# class ValueTooSmallError inherits from class MyError
class ValueTooSmallError(MyError):
  """Raised when the input value is too small"""
  pass

# class ValueTooLargeError inherits from class MyError
class ValueTooLargeError(MyError):
  """Raised when the input value is too large"""
  pass

# you need to guess this number
number = 5

# user guesses a number until user gets it right
while True:
  try:
    i_num = int(input("Enter a number: "))
    if i_num < number:
      raise ValueTooSmallError("This value is too small, try again!")
    elif i_num > number:
      raise ValueTooLargeError("This value is too large, try again!")
    break
  except ValueTooSmallError as error:
    print(error.message)
  except ValueTooLargeError as error:
    print(error.message)

print("Congratulations! You guessed it correctly.")
Kết quả
Enter a number: 9
This value is too large, try again!
Enter a number: 7
This value is too large, try again!
Enter a number: 3
This value is too small, try again!
Enter a number: 5
Congratulations! You guessed it correctly.

Trong ví dụ trên, chúng ta có một lớp User-Defined Exception là MyError. MyError tiếp tục được kế thừa bởi các lớp User-Defined Exception là ValueTooSmallErrorValueTooLargeError.

5/5 - (1 bình chọn)
Bài trước và bài sau trong môn học<< Nạp chồng toán tử (operator overloading) trong PythonMở (open) và đọc (read) tập tin (file) với Python >>
Chia sẻ trên mạng xã hội:

Trả lời

Lưu ý:

1) Vui lòng bình luận bằng tiếng Việt có dấu.

2) Khuyến khích sử dụng tên thật và địa chỉ email chính xác.

3) Mọi bình luận trái quy định sẽ bị xóa bỏ.