Python的异常处理
来源:互联网 发布:静态网页源码 编辑:程序博客网 时间:2024/05/29 15:48
1.raise语句
为了引发异常,可以使用一个类或者实例调用raise语句。
raise Exception
Traceback (most recent call last): File "<stdin>", line 1, in <module>Exception
raise Exception('hyperdive overload')
Traceback (most recent call last): File "<stdin>", line 1, in <module>Exception: hyperdive overload
2.捕捉异常
try: x=input() y=input() print x/yexcept ZeroDivisionError: print "The second number can't be zero"2
0
The second number can't be zero
3.捕捉多个异常
上述代码只忽略了除数为0的异常,对于其他的异常,依然会出错
所以,我们可以再添加一个except语句,捕捉类型异常
try: x=input() y=input() print x/yexcept ZeroDivisionError: print "The second number can't be zero"except TypeError: print "That wasn't a number..."
或者,在一个except语句里,多添加几个异常
try: x=input() y=input() print x/yexcept(ZeroDivisionError,TypeError,NameError): print "Your numbers were bogus"
或者,异常全捕捉
try: x=input() y=input() print x/yexcept: print "Something wrong happend..."
3.如果你希望程序继续运行,但是又想记录下错误,可以捕捉对象
try: x=input() y=input() print x/yexcept(ZeroDivisionError,TypeError,NameError),e: print e
异常被打印,程序并没有报错
4.添加else字句,当不报错时,执行代码
while True: try: x=input() y=input() print x/y except: print "Invalid input.Please try again." else: break
在不报错的时候,退出循环
阅读全文
0 0
- python的异常处理
- python的异常处理
- Python的异常处理
- python的异常处理
- Python的异常处理
- Python的异常处理
- python异常的处理
- python的异常处理
- Python的异常处理
- Python的异常处理
- Python的异常处理
- python 异常的处理
- Python的异常处理
- python的异常处理机制
- Python的异常处理机制
- python的异常处理流程
- Python的异常处理机制
- python的异常处理机制
- sort()函数 多个元素排序比较
- 解决 'boost/iterator/iterator_adaptor.hpp' file not found’ 及控制台":CFBundleIdentifier", Does Not Exist
- 图像中噪声分类
- hihoCoder挑战赛31 题解
- Markdown 语法之基本文本编译篇
- Python的异常处理
- 【POJ 2112 Optimal Milking】网络流 & 二分 & floyd
- 海量数据处理
- Codeforces Round #437 (Div. 2, based on MemSQL Start[c]UP 3.0
- 解决No module named google.protobuf.internal
- (crm笔记1-2) Dao层的搭建
- 并行计算及其发展
- wc命令的C语言实现
- 记录一次问题