Python自定义异常类创建与捕获实战指南
本文详细讲解Python中如何创建用户自定义异常类。通过继承内置的Exception类,开发者可以定义特定的异常类型,并在代码中使用raise语句手动抛出。结合try-except结构,能够精准捕捉并处理这些自定义错误,提升程序的健壮性与错误提示的可读性。
说明
在Python中,程序可以通过定义新的异常类来命名自定义的错误。通常情况下,这些自定义异常类应当以直接或间接的方式继承自内置的Exception基类。
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如何自定义异常的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









