异常

异常处理与Python编程实践
本文深入探讨了异常处理在程序执行中的作用,通过Python代码示例解释了如何使用try...except语句来捕获和处理运行时错误,确保程序的稳定性和健壮性。

异常:
程序执行的时候,出现了错误。
出现了异常,程序报错,然后中断执行。

异常和程序错误,完全等价么?
异常时程序错误的一种

>>> try:
...     1/0  #出现错误了
...     print("hello")
...     print("world")
... except:
...     print("error occur!")
...
error occur!
>>> print("done!")
done!

出现错误了就跳出try去执行except里面的语句。

>>> try:
...     1/0  #出现错误了
...     print("hello")
...     print("world")
... except TypeError:
...     print("error occur!")
... except ZeroDivisionerror:
...     print("ZeroDivisionerror occur!")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NameError: name 'ZeroDivisionerror' is not defined
>>> print("done!")
done!
>>> try:
...     int("a")  #出现错误了
...     print("hello")
...     print("world")
... except TypeError:
...     print("error occur!")
... except ZeroDivisionerror:
...     print("ZeroDivisionerror occur!")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'a'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NameError: name 'ZeroDivisionerror' is not defined
>>> print("done!")
done!
>>> try:
...     int("a")  #出现错误了
...     print("hello")
...     print("world")
... except ValueError:
...     print("value error!")
... except ZeroDivisionerror:
...     print("ZeroDivisionerror occur!")
...
value error!
>>> print("done!")
done!

异常只会被拦截一次,拦截后后面的except都不会背执行了,程序也会在执行except语句后,跳出try…except…后继续执行后续的代码。
小练习:
请输入2个数字,相加,打印结果。(不管用户输入什么,程序不能崩溃)
如果输入的不是数字,那么让用户再重新输入。
提示用while死循环。

result = ""
while 1:
    try:
        a = float(input("请输入数据a:"))
        break
    except:
        print("输入的数据不是数字类型,请重新输入。")


while 1:
    try:
        b = float(input("请输入数据b:"))
        break
    except:
        print("输入的数据不是数字类型,请重新输入。")

result = a+b
print(result)

在这里插入图片描述

>>> try:
...     1/0
... except TypeError:
...     print("TypeError occur!")
... except ValueError:
...     print("ValueError occur!")
... except Exception as e:
...     print(e)
...
division by zero
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值