错误:
- 语法
- 逻辑
异常: 因为程序出现了错误而在正常控制流以外采取的行为。
- 引起异常发生的错误
- 检测(和采取可能的措施)
运行时管理错误的能力
Python中的异常
- BaseException
- KeyboardInterrupt
- SystemExit
- Exception
- (all other current build-in exceptions)
例子:
- NameError: 尝试
访问一个未申请的变量 - ZeroDivisionError: 除数为零
- IndexError: 请求的索引超出序列范围
- KeyError: 请求一个不存在的字典关键字
- IOError: 输入/输出错误
- AttributeError: 尝试访问未知的对象属性
检测和处理异常
try-except
忽略代码,继续执行,和向上移交
注: try-except
的作用是提供一个可以++提示错误或处理错误++的机制,而不是一个错误过滤器!
else
子句
在try
范围中没有异常被检测到时,执行else
子句。
finally
子句
finally
子句是无论异常是否发生,是否捕捉都会执行的一段代码。
f = open(path, 'w')
try:
write_to_file(f)
except:
print 'Failed'
else:
print 'Succeeded'
finally:
f.close()
Python2.x
try:
wrong_name
except NameError, err:
print err
Python3.x
修改异常处理方式:使用as关键字标识异常信息
try:
wrong_name
except NameError as err:
print err
With
语句
with context_expr [as var]:
with_suite
注: 仅能工作于支持上下文管理协议(context management protocol)的对象。
- file
- decimal.Context
- thread.LockType
- threading.Lock
- threading.RLock
- threading.Condition
- threading.Semaphore
- threading.BoundedSemaphore
例:
with open('/etc/passwd', 'r') as f:
for eachLine in f:
pass #do stuff with eachLine or f..
raise
语句
raise [SomeException [, args [, traceback]]]
程序员明确的触发异常。
assert
帮助理解:想象为raise-if-not
等价于:断言成功不采取任何措施(类似语句),否则触发断言错误 AssertionError。