常见异常Error
- NameError
- ZeroDivisionError
- SyntaxError(唯一非运行时错误)
- IndexError
- KeyError
- IOErrpr
- OSError
- AttributeError
- ValueError
- TypeError
两个不是由错误引起的异常Error:
- SystemExit python程序需要退出
- KeyboardInterupt ctrl+C
异常类
- BaseExceptiom
- KeyboardInterrupt
- SystemExit
- Exception
- all other current build-in exceptions
try:
pass
except ValueError, reason:
print "%s" %str(reason)
except TypeError, reason:
print "%s" %str(reason)
except (IndexError, KeyError), reason:
print "%s" %str(reason)
except Exception, reason: #捕获所有异常, 不推荐使用空的except语句
print "%s" %str(reason)
else: #try 中没有异常的时候会执行else
print "No exceptions in try block"
finally: #无论如何都会执行到的代码,既是否有异常出现,都会执行
pass
触发异常
raise SomeException, args, traceback
raise exclass, args, tb
raise exclass()
raise exclass, instance
raise string, args, tb
断言
#assert = raise if not ...
#AssertError,断言引发的异常
asssert expression, arguments
assert 1==1
try:
pass
except AssertionError, args:
print '%s, %s' %(args.__class__.__name__, args)
sys模块
try:
pass
exception:
import sys
exc_tuple = sys.exc_info()
print exc_tuple
for item in exc_tuple:
print item
#(exc_type, exc_value, exc_traceback) = sys.exc_info()
#异常类,类实例,追踪记录对象
Reference
Python核心编程