สร้าง class สืบทอดจาก Exception
ตัวอย่างครบ: Guess the alphabet game
# Python user-defined exceptions
class CustomException(Exception):
"""Base class for other exceptions"""
pass
class PrecedingLetterError(CustomException):
"""Raised when entered alphabet is smaller than actual"""
pass
class SucceedingLetterError(CustomException):
"""Raised when entered alphabet is larger than actual"""
pass
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!")
except SucceedingLetterError:
print("The entered alphabet is succeeding one, try again!")
print("Congratulations! You guessed it correctly.")