异常:
程序执行的时候,出现了错误。
出现了异常,程序报错,然后中断执行。
异常和程序错误,完全等价么?
异常时程序错误的一种
>>> 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
异常处理与Python编程实践
本文深入探讨了异常处理在程序执行中的作用,通过Python代码示例解释了如何使用try...except语句来捕获和处理运行时错误,确保程序的稳定性和健壮性。
1万+

被折叠的 条评论
为什么被折叠?



