抛出自定义的异常-python基础第15单元-异常及模块
抛出自定义的异常你可以用raise语句来引发一个异常。异常/错误对象必须有一个名字,且它们应是Error或Exception类的子类下面是一个引发异常的例子: class ShortInputException(Exception): '''自定义的异常类''' def __init__(self, length, atleast): #super().__init__() self.length = length self.atleast = atleast def main(): try: s = input('请输入--> ') if len(s) < 3: # raise引发一个你定义的异常raise ShortInputException(len(s), 3) except ShortInputException as result:#x这个变量被绑定到了错误的实例print('ShortInputException:输入的长度是%d,长度至少应是%d'% (result.length, result.atleast)) else: print('没有异常发生.') main()
1.05MB
文件大小:
评论区