如何在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 婆婆高寿祝福语大全简短