python 异常处理、assert应用、常见异常

来源:互联网 发布:php is numeric 漏洞 编辑:程序博客网 时间:2024/05/18 17:55

1.异常的基础语法

try:    pass;except Exception,e:    pass;finally:    pass;

2.异常其他结构:

try:    # 主代码块    passexcept KeyError,e:    # 异常时,执行该块    passelse:    # 主代码块执行完,执行该块    passfinally:    # 无论异常与否,最终执行该块    pass

3.触发异常

raise 

4.自定义异常:

# -*- coding:utf-8 -*-# __author__ = 'Administrator'class MyException(Exception):    def __init__(self,msg):        self.message = msg;    def __str__(self):        return self.message;try:    assert 1==1;    #自定义触发异常    raise MyException("自定义异常");except MyException,e:    print e;finally:    print "不论前面的是否错误都会执行......";

5.断言assert

# -*-coding:utf8 -*-# __author__ = 'Administrator'#目的1.调试#目的2.可以判断前面的某个条件是否成立,说白了也是调试print "a";assert 1==2;print "b";

6.异常种类

AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性xIOError 输入/输出异常;基本上是无法打开文件ImportError 无法引入模块或包;基本上是路径问题或名称错误IndentationError 语法错误(的子类) ;代码没有正确对齐IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]KeyError 试图访问字典里不存在的键KeyboardInterrupt Ctrl+C被按下NameError 使用一个还未被赋予对象的变量SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)TypeError 传入对象类型与要求的不符合UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它ValueError 传入一个调用者不期望的值,即使值的类型是正确的

ArithmeticErrorAssertionErrorAttributeErrorBaseExceptionBufferErrorBytesWarningDeprecationWarningEnvironmentErrorEOFErrorExceptionFloatingPointErrorFutureWarningGeneratorExitImportErrorImportWarningIndentationErrorIndexErrorIOErrorKeyboardInterruptKeyErrorLookupErrorMemoryErrorNameErrorNotImplementedErrorOSErrorOverflowErrorPendingDeprecationWarningReferenceErrorRuntimeErrorRuntimeWarningStandardErrorStopIterationSyntaxErrorSyntaxWarningSystemErrorSystemExitTabErrorTypeErrorUnboundLocalErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeErrorUnicodeTranslateErrorUnicodeWarningUserWarningValueErrorWarningZeroDivisionError
在python的异常中,有一个万能异常:Exception,他可以捕获任意异常,即:
s1 = 'hello'
try:
    int(s1)
except Exception,e:
    print e
0 0
原创粉丝点击