zoukankan      html  css  js  c++  java
  • 第十一章 Python之异常处理

    异常

      异常时程序运行时发生错误的信号(在程序错误时,则会产生一个异常,若程序没有处理,则会抛出该异常,程序的运行也随之终止)

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

    异常处理

      如果错误发生的条件是可预知的,需要用if进行处理,在错误发生之前进行预防

      如果错误发生的条件是不可预知的,则需要用try...except,在错误发生之后进行处理

    try:
        被检测的代码
    except 异常类型:
        一旦检测到该类型的异常,则执行这个位置的逻辑
    try:
        l=[]
        print(l[111])
    except IndexError:
        print('下标索引超出序列边界')
    try:
        l=[]
        print(l[111])
    except IndexError as e:   #获取异常值
        print(e)
    try:
        d={}
        print(d['k'])
    except IndexError as e:    #可以写多个except捕获异常
        print(e)
    except KeyError as e:      #可以写多个except捕获异常
        print(e)
    try:
        d={}
        print(d['k'])
    except Exception as e:      #万能异常,可以捕获所有异常
        print(e)
    try:
        d={}
        print(d['k'])
    except Exception as e:
        print(e)
    else:
        print('没有异常')       #没有异常的时候触发
    finally:
        print('结束')          #有无异常都触发
    stus=[]
    try:
        if len(stus) == 0:
            raise TypeError('列表元素为0')   #主动触发异常
    except Exception as e:
        print(e)
    #stus=[]
    stus=['1']
    assert len(stus) > 0    #断言,符合断言则执行后面的代码,不符合则抛出异常
    print('大于0')
    class MyException(BaseException):
        def __init__(self,msg):
            super(MyException,self).__init__()
            self.msg=msg
    
        def __str__(self):
            return '<%s>'%self.msg
    
    raise MyException('自定义异常')
  • 相关阅读:
    手写一个类django框架
    Django基础知识
    JQuery知识点总结
    javascript知识点整理
    html知识点一
    mysql之sql语句
    通过非IO阻塞模型实现ftp并发的小代码
    python学习第三十三节(IO模型)
    python学习第三十二节(进程间通信、进程池、协程)
    IntelliJ IDEA For Mac 快捷键
  • 原文地址:https://www.cnblogs.com/iamluoli/p/8397984.html
Copyright © 2011-2022 走看看