python用户自定义异常的实例讲解
说明
1、程序可以通过创建一个新的异常类来命名它们自己的异常。异常应该是典型的继承自Exception类,直接或间接的方式。
2、异常python有一个大基类,继承了Exception。因此,我们的定制类也必须继承Exception。
实例
class ShortInputException(Exception): def __init__(self, length, atleast): 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.用户自定义异常类型,只要该类继承了Exception类即可,至于类的主题内容用户自定义,可参考官方异常类 class TooLongExceptin(Exception): "this is user's Exception for check the length of name " def __init__(self,leng): self.leng = leng def __str__(self): print("姓名长度是"+str(self.leng)+",超过长度了")
捕捉用户手动抛出的异常
#1.捕捉用户手动抛出的异常,跟捕捉系统异常方式一样 def name_Test(): try: name = input("enter your naem:") if len(name)>4: raise TooLongExceptin(len(name)) else : print(name) except TooLongExceptin,e_result: #这里异常类型是用户自定义的 print("捕捉到异常了") print("打印异常信息:",e_result) #调用函数,执行 name_Test() ==========执行结果如下:================================================== enter your naem:aaafsdf 捕捉到异常了 Traceback (most recent call last): 打印异常信息: 姓名长度是7,超过长度了 姓名长度是7,超过长度了 File "D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py", line 16, in name_Test raise TooLongExceptin(len(name)) __main__.TooLongExceptin: <exception str() failed> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py", line 26, in <module> name_Test() File "D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py", line 22, in name_Test print("打印异常信息:",e_result) TypeError: __str__ returned non-string (type NoneType)
以上就是python用户自定义异常的实例讲解的详细内容,更多关于python用户如何自定义异常的资料请关注我们其它相关文章!
赞 (0)