Giống như các ngôn ngữ bậc cao khác, Python cũng có các ngoại lệ. Khi có vấn đề xảy ra, nó ném một ngoại lệ. Có nhiều loại ngoại lệ như ZeroDivisionError, AssertionError v.v. Tất cả các lớp ngoại lệ đều kế thừa từ lớp BaseException.
Mã có thể chạy các ngoại lệ built-in, hoặc ta cũng có thể ném các ngoại lệ này trong mã. Người dùng có thể tự định nghĩa ngoại lệ riêng từ lớp Exception, hoặc từ bất kỳ lớp con nào của Exception.
BaseException là lớp cơ sở của tất cả các ngoại lệ khác. Các lớp do người dùng định nghĩa không thể kế thừa trực tiếp từ lớp này; để định nghĩa lớp riêng, ta cần dùng lớp Exception.
Hệ thống phân cấp ngoại lệ Python như sau:
- 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
- IndentationError
- SystemError
- TypeError
- ValueError
- UnicodeError
- UnicodeDecodeError
- UnicodeEncodeError
- UnicodeTranslateError
- UnicodeError
- Warning
- BytesWarning
- DeprecationWarning
- FutureWarning
- ImportWarning
- PendingDeprecationWarning
- ResourceWarning
- RuntimeWarning
- SyntaxWarning
- UnicodeWarning
- UserWarning
- GeneratorExit
- KeyboardInterrupt
- SystemExit
- ArithmeticError
Bài toán - Có một lớp nhân viên. Điều kiện: tuổi nhân viên phải lớn hơn 18.
Ta nên tạo một lớp ngoại lệ do người dùng định nghĩa, là lớp con của lớp Exception.
Ví dụ mã
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))
Kết quả
The name of the employee: Subhas, Age: 25 Years Error Occurred: The age must be greater than 18 years