python--例外管理(try、except、else、finally的关系)和例外的引发

一、try、except、else、finally的关系

#执行try,若发生FileNotFoundError类型的例外,则进行相应处理
try:f=open(arg,'r')
except FileNotFoundError:#except:则对应所有的例外(BaseException)print("找不到文件",arg)
else:#若try顺利执行,则执行else的内容try:print(arg,'有',len(f.readline()),'行')finally:#无论try是否产生意外,都会执行finally,即使try内定义return,也会先执行finally再返回f.close()

二、自定义例外类型,并进行引发

class Account:def __init__(self,name,number,balance):self.name=nameself.number=numberself.balance=balance#定义参数检查金额的正负def check_amount(self,amount):if amount <=0:raise  IllegalMoneyException('金额必须为正数:'+str(amount))def deposit(self,amount):self.check_amount(amount)self.balance+=amountdef withdraw(self,amount):self.check_amount(amount)#当出现余额不足时,引发自定义例外。此处可扩展进行借贷事项if amount>self.balance:raise  InsufficientException('余额不足')self.balance-=amountdef __str__(self):#定义对象的输出描述return "Account('{name}','{number}','{balance}')".format(name=self.name,number=self.number,balance=self.balance)
#自定义两个例外类型,继承于BaseException。
##初始化时注意调用super()将参数传递给其父类的__init__()
class IllegalMoneyException(BaseException):def __init__(self,message):super().__init__(message)
class InsufficientException(BaseException):def __init__(self,message):super().__init__(message)

定义文件测试

x=Account('Justin','123-456',500)
print(x)
x.deposit(300)
print(x)
x.deposit(-300)
print(x)

测试运行结果:

Account('Justin','123-456','500')
Account('Justin','123-456','800')#前四句语句正常执行File "D:/python/python project/openhome/mathdemo.py", line 36, in x.deposit(-300)File "D:/python/python project/openhome/mathdemo.py", line 11, in depositself.check_amount(amount)File "D:/python/python project/openhome/mathdemo.py", line 9, in check_amountraise  IllegalMoneyException('金额必须为正数:'+str(amount))
__main__.IllegalMoneyException: 金额必须为正数:-300


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部