Python札记43_错误与异常

在程序执行的过程中因为错误或者其他原因而导致中止的行为,都归纳为“错误和异常”。

错误与异常

  • 错误
    • 语法错误
    • 逻辑错误

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语句。


image.png
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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容