您的位置:首页 > 编程语言 > Python开发

<PY><core python programming笔记>C10 错误和异常

2014-05-23 17:14 711 查看

C10 错误和异常

10.1 异常处理

try ----catching

原因:程序可能被中止,错误可能向上层传播

目的:使程序继续运行,避免错误传播,把错误转化为“非错误”

一旦程序出错就直接到到expect之后,所有要设计好except

except相当于一个异常处理器

#不要处理忽略所有错误,因为可能发生未知的异常,忽略就真的传播扩散了

10.2Python中之异常

NameError 尝试访问一个未声明的变量

ZeroDivisionError 除法0溢出(除数为0)

SyntaxError 解释器语法错误

IndexError 索引超出范围

KeyError 请求了一个不存在的字典关键字

IOError 输入/输出错误

AttributeError 尝试访问未知的对象属性

10.3检测异常(解释器触发)

try-except-except

try-except-except-finally #finally是总会执行的

try-except-else #else是无异常时执行

try-finally(finally没有异常处理) #直接finally,异常留给上层

try-except-except-else-finally

except (ex1,ex2,ex3)[,reason]: #多错误共同处理

suite_for_Exception1_and_Exception2_and

try:

f=open('blah','r')

except IOError,e: #e是异常处理器提供的内容

print 'could not open file:',e

def safe_float(obj):

try:

return float(obj)

except ValueError:

pass #忽略float格式化错误

def safe_float(obj):

try:

retval=float(obj)

except ValueError:

retval=None #至少要显示返回None,也可以返回错误提示字符串

return retval

def safe_float(obj): #多异常分别处理

try:

retval=float(obj)

except ValueError:

retval='could not convert non-number to float'

except TypeError:

retval='object type cannot be converted to float'

return retval

except Exception,e: #捕获所有错误(推荐),或者空except(不推荐)

#但后来不是所有了 还有 KeyboardInterrupt和SystemExit等

#所以换成 except BaseException,e:

10.4上下文管理

with语句

10.6手动触发异常

raise [SomeException,[,args[,traceback]]]

raise 可以重新触发前一个异常

10.7断言

assert #可以简单的理解 raise-if-not

10.12可以从 sys.exc_info()中获取异常信息

except:

import sys

exc_tuple=sys.exc_info()

10.13相关模块

exceptions

contextlib

sys
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: