内容简介:python-异常处理try_except
异常处理try-except
在我们写程序的时候经常会遇到一些异常或错误,导致程序终止
当我们使用计算器时,用10除以0会提示
一个简单的错误代码 (10/0)
a = 10 / 0
print("done")
输出报错:
a = 10 / 0
ZeroDivisionError: division by zero
可以发现错误信息ZeroDivisionError中断了done的输出
为了处理这个异常,我们可以使用try_except来捕捉这个异常
try:
c = 10 / 0
print(c)
except ZeroDivisionError as e:
print("除数不能为零")
#print(e)
print("done")
输出结果:
除数不能为零
done
注意:在 Python 2.5之前的版本中需要将 ZeroDivisionError as e改为ZeroDivisionError, e,(后面的e代表异常的实例)
try_except_else语句
try:
c = 10 / 1
except ZeroDivisionError as e:
print(e)
else:
print("没有报错信息【c=%s】" % c)
print("done")
输出结果
没有报错信息【c=10.0】
done
从以上可以看出,如果没有出现异常,就执行else内容,报错则执行except的内容
以上所述就是小编给大家介绍的《python-异常处理try_except》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Smashing Book
Jacob Gube、Dmitry Fadeev、Chris Spooner、Darius A Monsef IV、Alessandro Cattaneo、Steven Snell、David Leggett、Andrew Maier、Kayla Knight、Yves Peters、René Schmidt、Smashing Magazine editorial team、Vitaly Friedman、Sven Lennartz / 2009 / $ 29.90 / € 23.90
The Smashing Book is a printed book about best practices in modern Web design. The book shares technical tips and best practices on coding, usability and optimization and explores how to create succes......一起来看看 《The Smashing Book》 这本书的介绍吧!