如何在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 生日广州男生祝福语简短