python-异常处理try_except
2020-01-12 10:11
337 查看
异常处理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
注意:在Python2.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的内容
转载于:https://www.cnblogs.com/smelond/p/8324944.html
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- python异常的捕获处理 try-except-else-finally的完整用法
- Python异常处理try...except、raise
- python异常处理try,except,else,finally,raise
- python异常处理try,except,else,finally,raise
- Python中的异常处理: try-except-else-finally
- Python异常处理(二)——try...except 处理异常、异常类的继承、else、finally回收资源
- 【】Python】异常处理try...except、raise
- python try...except....else...finally处理异常
- 【python学习笔记】Python异常处理raise、try...except、断言assert
- Python异常处理try...except...finally raise assert
- (Python)异常处理try...except、raise
- Python异常处理try...except、raise
- python异常处理 try.....except
- Python 异常处理方法try&except
- python基础——try与except处理异常语句详解
- (Python)异常处理try...except、raise
- Python中异常处理简单示例(try,except,finally)
- python基础知识三——try与except处理异常语句
- python 异常处理-try-except-else-finally
- Python异常处理try...except、raise