Python——raise引发异常
程序出现错误,会⾃动引发异常,Python也允许使⽤raise语句⾃⾏引发异常。
⼀、使⽤raise引发异常
单独⼀个raise引发异常,默认引发RuntimeError异常,例:
try:
print ('正在运⾏try块...')
raise
print ('不再运⾏...')
except Exception as e:
print ('正在运⾏except块...')
# 运⾏结果
正在运⾏try块...
正在运⾏except块...
raise后带⼀个异常类,引发指定异常类的默认实例,例:
def test():
try:
print ('正在运⾏try块...')
raise SyntaxError('引发指定异常...')
print ('不再运⾏...')
except TypeError as e:
print ('对类型⽆效的操作...',e)
except ValueError as e:
print ('传⼊⽆效的参数...',e)
except SyntaxError as e:
syntaxerror是什么错误
print ('语法错误...',e)
test()
# 运⾏结果
正在运⾏try块...
语法错误... 引发指定异常...
⼆、⾃定义异常类
Python运⾏⾃定义异常类,⾃定义异常都应该继承Exception基类或Exception的⼦类,⾃定义类⼤部分情况下都可以采⽤AuctionException.py类似的代码来完成,只要改变AuctionException异常的类名即可(使类名更准确的描述该异常)。
⾃定义⼀个异常类,例:
class CustomException(Exception):
pass
def test():
try:
raise CustomException
except CustomException:
print ('触发异常...')
test()
# 运⾏结果
触发异常...
三、except和raise组合使⽤
当出现⼀个异常时,单单靠⼀个⽅法⽆法完全处理该异常,必须使⽤⼏个⽅法协作才能完全处理该异常时,就⽤到except块结合raise语句来完成。
例:
# ⾃定义异常
class CustomException(Exception):
pass
class Test:
def custom(self):
try:
aaa
except Exception as e:
print ('出现异常:',e)
raise CustomException('触发⾃定义异常~')
def test():
T = Test()
try:
T.custom()
except CustomException as e:
print ('test函数捕获异常;',e)
test()
# 打印
出现异常: name 'aaa' is not defined
test函数捕获异常;触发⾃定义异常~
  上⾯程序中,aaa触发了NameError异常,执⾏Test类中的except块,打印错误信息后,通知该⽅法调⽤者再次处理CustomException 异常,所以custom()⽅法的调⽤者test()函数可以再次捕获CustomException异常,把异常详细信息打印出来。