常见的异常类型:
还可以自己使用raise来触发异常
示例:
def set_age(num):
if num<=0 or num>=200:
#抛出VauleError
raise ValueError(f"值错误:{num}")
else:
print(f"设置年龄为:{num}")
set_age(-1)
运行结果:
#----------------------------------------------
Traceback (most recent call last):
File "D:\HogwartsTrainingCampPytest\pythondemo\demo.py", line 13, in <module>
set_age(-1)
File "D:\HogwartsTrainingCampPytest\pythondemo\demo.py", line 9, in set_age
raise ValueError(f"值错误:{num}")
ValueError: 值错误:-1
创建自定义错误类并继承Exception:
#继承Exception
class MyError(Exception):
def __init__(self,value):
self.value=value
def __str__(self):
return repr(self.value)
示例:
class MyError(Exception):
def __init__(self,msg):
print(f"这是一个异常:{msg}")
def set_age(num):
if num<=0 or num>=200:
#抛出自定义的异常
raise MyError(f"值错误:{num}")
else:
print(f"设置年龄为:{num}")
set_age(-1)
运行结果:
#----------------------------------------------
这是一个异常:值错误:-1
Traceback (most recent call last):
File "D:\HogwartsTrainingCampPytest\pythondemo\demo.py", line 13, in <module>
set_age(-1)
File "D:\HogwartsTrainingCampPytest\pythondemo\demo.py", line 9, in set_age
raise MyError(f"值错误:{num}")
__main__.MyError: 值错误:-1