【python二级】错误及错误处理

语言程序错误

1、语法错误

2、运行错误

运行过中程序意外终止的错误,最常见的有1/0

1/0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_12736/2354412189.py in <module>
----> 1 1/0


ZeroDivisionError: division by zero

避免运行错误

为了避免因为出现运行错误,而导致的整个程序瘫痪,可以使用try-except-else 代码块。
try代码块中只包含可能出现错误的代码,except代码块表示出现错误(ZeroDivisionError、FileNotFoundError等)时要怎么办,else代码块只运行try代码块可以运行成功的代码。
还是以0做除数为例,创建一个只执行除法运算的简单计算器:

x = input("input the first number:")
y = input("input the second number")
try:
    z=int(x)/int(y)
except ZeroDivisionError:
    print("You can't divide by 0!")
else:
    print(z)

还可以加入while语句,实现连续输入

while True:
    x = input("input the first number:")
    y = input("input the second number")
    try:
        z=int(x)/int(y)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(z)

静默错误

有时候你希望程序在发生异常时保持静默,就像什么都没有发生一样继续运行,只需要在except语句中输入pass就可以了!

while True:
    x = input("input the first number:")
    y = input("input the second number")
    try:
        z=int(x)/int(y)
    except ZeroDivisionError:
        pass
    else:
        print(z)

3、逻辑错误

程序跑出来了,但结果是错的,就是逻辑错误啦!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值