在程序的编写中难免会出现一些未能预测到情况,如果没有捕获这些异常会影响到程序的运行,在Python中也有对应的异常捕获功能。
Python 基本的异常捕获结构是try … except, 这里有不同的异常模块,最常见的模块是Exception,它可以捕获任意异常。如果except后没有指定异常,则默认处理所有的异常。同时,对于每一个try,都必须至少有一个except。
Python 基本异常结构:
s1 = 'www.cndba.cn'
try:
int(s1)
except Exception as e:
print 'MSG:',e
#output:
ssh://root@192.168.20.15:22/usr/bin/python -u /dave/orz/test.py
MSG: invalid literal for int() with base 10: 'www.cndba.cn'
如果要处理多个异常,可以多次捕获,代码如下:
s1 = 'www.cndba.cn'
try:
int(s1)
except IndexError,e:
print 'IndexError:',e
except KeyError,e:
print 'KeyError:',e
except ValueError,e:
print 'ValueError:',e
#output:
ssh://root@192.168.20.15:22/usr/bin/python -u /dave/orz/test.py
ValueError: invalid literal for int() with base 10: 'www.cndba.cn'
注意对于多个异常的捕获,建议先捕获特殊的异常,最后定义Exception,已确保程序能正常运行。
s1 = 'www.cndba.cn'
try:
int(s1)
except KeyError,e:
print '键错误'
except IndexError,e:
print '索引错误'
except Exception, e:
print '错误'
复杂结构的异常:
try:
# 主代码块
pass
except KeyError,e:
# 异常时,执行该块
pass
else:
# 主代码块执行完,执行该块
pass
finally:
# 无论异常与否,最终执行该块
pass
除了被动的等待异常之外,也可以主动触发异常,直接使用raise Exception(‘messages’) 即可,示例如下:
s1 = 'www.cndba.cn'
try:
if len(s1) > 8:
raise ValueError('the length of the domain is more than 8')
except Exception,e:
print e
自定义异常
s1 = 'www.cndba.cn'
class cndbaException(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
try:
raise cndbaException('welcome to cndba community:'+s1)
except cndbaException,e:
print e
最后附上Python 所有的标准异常类,可以根据需要进行使用:
异常名称 | 描述 |
---|---|
BaseException | 所有异常的基类 |
SystemExit | 解释器请求退出 |
KeyboardInterrupt | 用户中断执行(通常是输入^C) |
Exception | 常规错误的基类 |
StopIteration | 迭代器没有更多的值 |
GeneratorExit | 生成器(generator)发生异常来通知退出 |
SystemExit | Python 解释器请求退出 |
StandardError | 所有的内建标准异常的基类 |
ArithmeticError | 所有数值计算错误的基类 |
FloatingPointError | 浮点计算错误 |
OverflowError | 数值运算超出最大限制 |
ZeroDivisionError | 除(或取模)零 (所有数据类型) |
AssertionError | 断言语句失败 |
AttributeError | 对象没有这个属性 |
EOFError | 没有内建输入,到达EOF 标记 |
EnvironmentError | 操作系统错误的基类 |
IOError | 输入/输出操作失败 |
OSError | 操作系统错误 |
WindowsError | 系统调用失败 |
ImportError | 导入模块/对象失败 |
KeyboardInterrupt | 用户中断执行(通常是输入^C) |
LookupError | 无效数据查询的基类 |
IndexError | 序列中没有没有此索引(index) |
KeyError | 映射中没有这个键 |
MemoryError | 内存溢出错误(对于Python 解释器不是致命的) |
NameError | 未声明/初始化对象 (没有属性) |
UnboundLocalError | 访问未初始化的本地变量 |
ReferenceError | 弱引用(Weak reference)试图访问已经垃圾回收了的对象 |
RuntimeError | 一般的运行时错误 |
NotImplementedError | 尚未实现的方法 |
SyntaxError | Python 语法错误 |
IndentationError | 缩进错误 |
TabError | Tab 和空格混用 |
SystemError | 一般的解释器系统错误 |
TypeError | 对类型无效的操作 |
ValueError | 传入无效的参数 |
UnicodeError | Unicode 相关的错误 |
UnicodeDecodeError | Unicode 解码时的错误 |
UnicodeEncodeError | Unicode 编码时错误 |
UnicodeTranslateError | Unicode 转换时错误 |
Warning | 警告的基类 |
DeprecationWarning | 关于被弃用的特征的警告 |
FutureWarning | 关于构造将来语义会有改变的警告 |
OverflowWarning | 旧的关于自动提升为长整型(long)的警告 |
PendingDeprecationWarning | 关于特性将会被废弃的警告 |
RuntimeWarning | 可疑的运行时行为(runtime behavior)的警告 |
SyntaxWarning | 可疑的语法的警告 |
UserWarning | 用户代码生成的警告 |
版权声明:本文为博主原创文章,未经博主允许不得转载。