异常是因程序出现了错误而在正常控制流以外采取的行为,分为两个阶段:引起异常发生的错误阶段和检测阶段。
Python中常见的异常有:
NameError: 尝试访问一个未初始化的变量
ZeroDivisionError: 除数为零
SyntaxError: Python解释器语法错误
IndexError: 请求的索引超出序列范围
KeyError: 请求一个不存在的字典关键字
IOError: 输入/输出错误
AttributeError: 尝试访问未知的对象属性
检测和异常处理:try-except语句
...try:
...     try_suite    #监控这里的异常
...except: Exception[, reason]:
...     except_suite    #异常处理代码
例如:
...try:
...     f = open('blah', 'r')
...except IOError, e:
...     print 'could not open file:', e
打印为:
could not open file: [Errno 2] No such file or directory
Thursday, March 12, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment