Chúng ta tạo user-defined hoặc custom exceptions bằng cách tạo một exception class mới trong Python. Ý tưởng là derive custom exception class từ exception class. Hầu hết built-in exceptions dùng cùng ý tưởng để enforce exceptions của chúng.
Trong code cho trước, bạn đã tạo user-defined exception class, CustomException. Nó dùng Exception class làm parent. Do đó, custom exception class mới sẽ raise exceptions như bất kỳ exception class nào khác tức là bằng cách gọi statement raise với optional error message.
Hãy lấy ví dụ.
Trong ví dụ này, chúng ta show cách raise user-defined exception và catch errors trong chương trình. Cũng, trong sample code, chúng ta hỏi user nhập alphabet lại và lại cho đến khi họ nhập đúng alphabet đã lưu.
Để giúp đỡ, chương trình cung cấp hint cho user để họ figure out alphabet đúng.
# Python user-defined exceptions
class CustomException(Exception):
"""Base class for other exceptions"""
pass
class PrecedingLetterError(CustomException):
"""Raised when entered alphabet is smaller than actual one"""
pass
class SucceedingLetterError(CustomException):
"""Raised when entered alphabet is larger than actual one"""
pass
# we need to guess this alphabet till we get it right
alphabet = 'k'
while True:
try:
foo = raw_input("Enter an alphabet: ")
if foo < alphabet:
raise PrecedingLetterError
elif foo > alphabet:
raise SucceedingLetterError
break
except PrecedingLetterError:
print("The entered alphabet is preceding one, try again!")
print('')
except SucceedingLetterError:
print("The entered alphabet is succeeding one, try again!")
print('')
print("Congratulations! You guessed it correctly.")