python-异常处理try_except

栏目: Python · 发布时间: 8年前

内容简介:python-异常处理try_except

异常处理try-except

在我们写程序的时候经常会遇到一些异常或错误,导致程序终止

当我们使用计算器时,用10除以0会提示

python-异常处理try_except

一个简单的错误代码 (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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Defensive Design for the Web

Defensive Design for the Web

37signals、Matthew Linderman、Jason Fried / New Riders / 2004-3-2 / GBP 18.99

Let's admit it: Things will go wrong online. No matter how carefully you design a site, no matter how much testing you do, customers still encounter problems. So how do you handle these inevitable bre......一起来看看 《Defensive Design for the Web》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试