一、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=name
self.number=number
self.balance=balance
#定义参数检查金额的正负
def check_amount(self,amount):
if amount <=0:
raise IllegalMoneyException('金额必须为正数:'+str(amount))
def deposit(self,amount):
self.check_amount(amount)
self.balance+=amount
def withdraw(self,amount):
self.check_amount(amount)
#当出现余额不足时,引发自定义例外。此处可扩展进行借贷事项
if amount>self.balance:
raise InsufficientException('余额不足')
self.balance-=amount
def __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 <module>
x.deposit(-300)
File "D:/python/python project/openhome/mathdemo.py", line 11, in deposit
self.check_amount(amount)
File "D:/python/python project/openhome/mathdemo.py", line 9, in check_amount
raise IllegalMoneyException('金额必须为正数:'+str(amount))
__main__.IllegalMoneyException: 金额必须为正数:-300