如何在Python中实现用户定义的异常?
我们通过在Python中创建新的异常类来创建用户定义或自定义异常。这个想法是从异常类派生自定义异常类。大多数内置异常使用相同的想法来实施其异常。
在给定的代码中,您已经创建了一个用户定义的异常类“CustomException”。它使用Exception类作为父类。因此,新的用户定义异常类将像其他任何异常类一样引发异常,即通过调用带有可选错误消息的“raise”语句。
让我们举个例子。
在此示例中,我们展示了如何引发用户定义的异常并捕获程序中的错误。同样,在示例代码中,我们要求用户一次又一次输入字母,直到他仅输入存储的字母。
为了获得帮助,该程序向用户提供了提示,以便他可以找出正确的字母。
#Python user-defined exceptions
class CustomException(Exception):
"""Base class for other exceptions"""
pass
class PrecedingLetterError(CustomException):
"""Raised when the entered alphabet is smaller than the actual one"""
pass
class SucceedingLetterError(CustomException):
"""Raised when the entered alphabet is larger than the 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.")热门推荐
10 老师对学校祝福语简短
11 叔叔生日祝福语简短励志
12 给宝贝开学祝福语简短
13 三八简短祝福语给婆婆
14 学生节祝福语大全简短
15 婚礼祝福语简短情话短句
16 孙子结婚奶奶祝福语简短
17 唯美的祝福语简短的
18 万寿祝福语简短