• 异常处理


    总结:不要依赖异常处理,只有在错误一定会发生,而且无法预知发生条件,导致一定会发生,还不能让该错误影响程序运行

    异常:错误发生的信号,程序一旦出错且未处理这个错误,就会抛出异常,且程序终止运行

    异常追踪信息:告知哪里出了错误

    异常类型:如ValueError,可以自定义

    异常值:异常值,告知具体的问题

    错误分类:

    1. 语法错误,py在执行前,都会对代码语法进行检测,在运行前需要改正
    2. 逻辑错误

    异常类型:

    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
    IOError 输入/输出异常;基本上是无法打开文件
    ImportError 无法引入模块或包;基本上是路径问题或名称错误
    IndentationError 语法错误(的子类) ;代码没有正确对齐
    IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
    KeyError 试图访问字典里不存在的键
    KeyboardInterrupt Ctrl+C被按下
    NameError 使用一个还未被赋予对象的变量
    SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
    TypeError 传入对象类型与要求的不符合
    UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
    导致你以为正在访问它
    ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    View Code
    ArithmeticError
    AssertionError
    AttributeError
    BaseException
    BufferError
    BytesWarning
    DeprecationWarning
    EnvironmentError
    EOFError
    Exception
    FloatingPointError
    FutureWarning
    GeneratorExit
    ImportError
    ImportWarning
    IndentationError
    IndexError
    IOError
    KeyboardInterrupt
    KeyError
    LookupError
    MemoryError
    NameError
    NotImplementedError
    OSError
    OverflowError
    PendingDeprecationWarning
    ReferenceError
    RuntimeError
    RuntimeWarning
    StandardError
    StopIteration
    SyntaxError
    SyntaxWarning
    SystemError
    SystemExit
    TabError
    TypeError
    UnboundLocalError
    UnicodeDecodeError
    UnicodeEncodeError
    UnicodeError
    UnicodeTranslateError
    UnicodeWarning
    UserWarning
    ValueError
    Warning
    ZeroDivisionError
    View Code

    异常处理:

    • 错误发送条件是可以预知的,应该用if判断去预防异常
    • 错误发送不可预知,应该用异常处理机制,try...except...,当异常类型和获取类型不相符,也无法获取异常

    多分枝处理异常:被监测的代码块,可能会抛出多种异常,并且针对每种类型定义单独逻辑

    try:
        print('===>1')
        # name
        print('===>2')
        l=[1,2,3]
        l[100]
        print('===>3')
        d={}
        d['name']
        print('===>4')
    except NameError as e:#将异常类型值赋值给变量e
        print("NameError")
        print(e)
    except IndexError as e:
        print('--->',e)
    except KeyError as e:
        print(e)
    View Code

    万能异常:Exception,可以涵盖各种异常。不管什么类型的异常,都用同一种逻辑去处理

    try:
        print('===>1')
        # name
        print('===>2')
        l=[1,2,3]
        l[100]
        print('===>3')
        d={}
        d['name']
        print('===>4')
    except Exception as e:
        print(e)
    View Code

    综合使用:先处理可知类型

    try:
        print('===>1')
        # name
        print('===>2')
        l=[1,2,3]
        l[100]
        print('===>3')
        d={}
        d['name']
        print('===>4')
    except NameError as e:#将异常类型值赋值给变量e
        print(e)
    except Exception as e:
        print(e)
    View Code

    其他逻辑

    try...except...else...:当监测代码块没有异常发生,则执行else逻辑

    try...except...else...finally...:不管是否有异常发生,都执行finally模块。通常用于回收资源

    try:
        print('===>1')
        int('ddd')
    except NameError as e:#将异常类型值赋值给变量e
        print(e)
    except Exception as e:
        print(e)
    else:
        print("在代码检测的代码中没有异常发生")
    finally:
        print("不管有无异常,都执行该代码块")
    View Code

    断言assert:下面代码依赖上面代码,通过assert判断

    info={}
    info['name']='ya'
    info['age']=18
    
    assert 'name' in info and 'age' in info#断言成功则执行,不成功则抛出异常
    
    if info['name']=='ya' and info['age']>10:
        print("wellcom")
    View Code

    主动触发异常:raise 异常类型(值)

    class People:
        def __init__(self,name,age,sex):
            if not isinstance(name,str):
                raise TypeError('名字必须传入str类型')
            if not isinstance(age,int):
                raise TypeError('年龄必须传入sint类型')
            self.name=name
            self.age=age
            self.sex=sex
    
    p=People(333,12,12)
    View Code

    自定义异常:raise方法会触发print(obj)方法,所以需要在自定义类型中定义一个__str__()方法

    class MyException(BaseException):
        def __init__(self,msg):
            super(MyException,self).__init__()
            self.msg=msg
        def __str__(self):
            return '<%s>' % self.msg
    raise MyException("我自己的异常类型")
    View Code
  • 相关阅读:
    Browsermob-Proxy 备忘
    Restic 备份工具
    GP刷新实体视图
    SDKMAN安装使用
    The requested module '/node_modules/.vite/vue.js?v=65afd58f' does not provide an export named 'default'
    Python——执行打包提示 ‘pyinstaller‘ 不是内部或外部命令,也不是可运行的程序
    python 打包exe 方法
    Python使用阿里云镜像
    使用Python项目生成所有依赖包的清单方式
    Git GuiUI的乱码问题如何解决
  • 原文地址:https://www.cnblogs.com/yaya625202/p/8939710.html
Copyright © 2020-2023  润新知