如何在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.")热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短