在程序执行的过程中因为错误或者其他原因而导致中止的行为,都归纳为“错误和异常”。
错误与异常
- 错误
- 语法错误
- 逻辑错误
当Python
解释器检测到错误,程序无法继续执行,就会抛出异常,查看Traceback
(回溯),常见的异常有:
异常 | 描述 |
---|---|
NameError | 变量没有声明 |
ZeroDivisonError | 除数是0 |
SyntaxError | 语法错误 |
IndexError | 索引超出序列范围 |
KeysError | 字典中的键不存在 |
IOError | 输入输出错误,比如文件不存在 |
AttributeError | 尝试访问位置对象的属性 |
处理异常
单个异常
while 1: # 条件一直为真
print("this is a divison program.")
c = input("please input 'c',otherwise logout:") # input输入的是字符串
if c == "c":
a = input("first number")
b = input("second number")
try:
print(float(a) / float(b))
print("*****************")
except ZeroDivisionError: #抛出除数是0的错误
print("the secon number can`t be zero")
print("*****************")
else: # 如果不满足if条件,退出程序
break
结果:
this is a divison program.
please input 'c',otherwise logout:c
first number4
second number2
2.0
*****************
this is a divison program.
please input 'c',otherwise logout:c
first number5
second number0
the secon number can`t be zero
*****************
this is a divison program.
please input 'c',otherwise logout:a # 退出程序
解释
- 关注try.....except.....语句
- try如果正常,执行里面的语句
- try如果异常,跳到except中执行后面的错误和子句
多个异常
捕获不同的异常,通过多个except进行处理
while 1:
print("this is a divison program.")
c = input("please input 'c',otherwise logout:")
if c == "c":
a = input("first number")
b = input("second number")
try:
print(float(a) / float(b))
print("*****************")
except ZeroDivisionError:
print("the secon number can`t be zero")
print("*****************")
# 增加部分:捕获输入非数字异常
except ValueError:
print("please input number.")
else:
break
结果
this is a divison program.
please input 'c',otherwise logout:c
first number:4 # 正常运行
second number:2
2.0
*****************
this is a divison program.
please input 'c',otherwise logout:c
first number:5
second number:hello # 输入非数字,报错
please input number. # 捕获异常
*****************
this is a divison program.
please input 'c',otherwise logout:a # 输入不是c,直接退出
- 当有多个except,try里面遇到一个异常,就会转到相应的except语句,同时程序终止。
- 除了使用多个except语句,还可以在except后面放置多个异常参数,通过
元组的形式
,一定要用元组的形式:
将上面的两个except语句改成如下形式:
except (ZeroDivision, ValueError): # 同时捕获多个异常
print("please input rightly.")
print("*********************")
- 默认的异常提示:
except (ZeroDivision, ValueError) as e: # 同时捕获多个异常
print(e)
print("*********************")
else语句
try:
print("I am try")
except:
print("I am except")
else:
print("I am else")
解释:
try
执行了,except
被跳过,else
执行了
while 1:
try:
x = input("first number:")
y = input("second number:")
z = float(x) / float(y)
print(z)
except Exception as e: # 如果出现异常,直接用内置的异常信息,e并打印出来; try里面出现了异常,被except捕获的话,else就不会执行
print(e)
print("input again")
else: # try执行没有问题就执行else
break
结果
first number:5
second number:0
float division by zero
input again
first number:3
second number:a
could not convert string to float: 'a'
input again
first number:4
second number:2
2.0
finally
有了finally,不管前面的try还是except,最终都要执行finally语句。
try:
print("I am try")
except:
print("I am except") # try异常
else:
print("I am else") # try没有异常
finally:
print("I am finally") # 一定会执行的
insert 断言
程序运行到某个节点的时候,就断定某个变量的值必然是什么。即判断某个东西必然是什么,如果不是就报错。insert
断言假定后面的语句是真的。
class Account: # 定义账户类
def __init__(self, number): # 初始化函数
self.number = number # 实例self的属性进行赋值,看做是用户的编号
self.balance = 0 # 给定一个balance的初值
# 存钱的操作,存入的钱amount加上初始值
def deposite(self, amount): # 传入参数amount
try:
assert amount > 0 # 断言amount大于0,否则报错,print语句
self.balance += amount # balance的初值加上amount;下面的方法中用到self.balance
except:
print("The money should be bigger than zero")
# 取钱的操作,上面的存款减去amount
def withdraw(self, amount):
assert amount > 0
if amount <= self.balance: # 修改self.balance 的值
self.balance -= amount
else:
print("balance is not enough")
if __name__ == "__main__":
a = Account(1000)
a.deposite(-10)
结果:
The money should be bigger than zero
修改下:
a = Account(1000) # 1000相当于是用户ID
a.deposite(2000) # 存钱
a.balance # 存入2000
a.withdraw(100) # 取出100
a.balance # 剩下1900