Python10

来源:互联网 发布:ubuntu wine安装 编辑:程序博客网 时间:2024/04/29 22:06

异常

异常可以通过try语句来检测,在try块里的代码都会被检测有无异常发生。try有两种主要形式:try-except 和try-finally,这两个相互排斥,只能选择其中一个。

try-except
try:    code #待监控代码except Exception1[,reason1]:    except_code1 #异常处理代码except Exception2[,reason2]:    except_code2 #异常处理代码...

例:

>>> try:...     handler=open('tmp','r')... except IOError as e:...     print(e)...     print(e.__class__)...     print(e.__class__.__doc__)...     print(e.__class__.__name__)     ...[Errno 2] No such file or directory: 'tmp'<class 'FileNotFoundError'>File not found.FileNotFoundError
else & finally

在else范围中的任何代码运行前,try范围中的所有代码必须完全成功,而finally则是无论异常是否发生,是否捕获都会执行。

>>> try:...     handle=open('tmp.info','r+')... except:...     print('open error')... else:...     print('open finish')...     handle.close()... finally:...     print('finally')...open errorfinally
assert

断言成功不采取任何措施,否则出发AssertionError异常,与c中assert类似。

assert expression[,arguments]

例:

>>> assert 1==0Traceback (most recent call last):  File "<stdin>", line 1, in <module>AssertionError>>> assert 1==0,'One is not equal Zero'Traceback (most recent call last):  File "<stdin>", line 1, in <module>AssertionError: One is not equal Zero>>> try:...     assert 1==2,'One is not equal Two'... except AssertionError as e:...     print('%s:%s' %(e.__class__.__name__,e))...AssertionError:One is not equal Two
标准异常
名 称 描 述 BaseException 所有异常的基类 SystemExit python解释器请求退出 KeyboardInterrupt 用户中断执行 Exception 常规错误的基类 StopIteration 迭代器没有更多的值 GeneratorExit 生成器发生异常来通知退出 StandardError 所有的内建标准异常的基类 ArithmeticError 所有数值计算错误的基类 FloatingPointError 浮点计算错误 OverflowError 数值运算超出最大限制 ZeroDivisionError 除(或取模)零 AssertionError 断言语句失败 AttributeError 对象没有这个属性 EOFError 没有内建输入,到达EOF标记 EnvirionmentError 操作系统错误基类 IOError 输入/输出操作失败 OSError 操作系统错误 WindowsError windows系统调用失败 ImportError 导入模块/对象失败 LookupError 无效数据查询的基类 IndexError 序列中没有次索引 KeyError 映射中没有这个键 MemoryError 内存溢出错误 NameError 为声明/初始化对象 UnboundLocalError 访问未初始化的本地变量 ReferenceError 弱引用驶入访问已经垃圾回收的对象 RuntimeError 一般运行时错误 NotImplementedError 尚未实现的方法 SyntaxError Python语法错误 IndentationError 缩进错误 TabError Tab和空格混用 SystemError 一般的解释器系统错误 TypeError 对类型无效的操作 ValueError 传入无效的参数 UnicodeError Unicode相关错误 UnicodeDecodeError unicode解码错误 UnicodeEncodeError unicode编码错误 UnicodeTranslateError unicode转换错误 Warning 警告基类 DeprecationWarning 关于被弃用的特征警告 FutureWarning 关于构造将来语义会有改变的警告 OverflowWarning 旧的关于自动提升为长整型的警告 PengingDeprecationWarning 关于特性将会被废弃的警告 RuntimeWarning 运行时警告 SyntaxWarning 可疑语法警告 UserWarning 用户代码生成警告
0 0
原创粉丝点击