zoukankan      html  css  js  c++  java
  • Python: 异常类型

    概述

    本文整理和参考自以下两篇博文:

    Python异常处理和异常类型
    python 异常类型(比较全)

    异常类型

    排序 名称 描述
    A ArithmeticError 所有数值计算错误的基类
    AssertionError 断言语句失败
    AttributeError 对象没有这个属性
    B BaseException 所有异常的基类
    D DeprecationWarning 关于被弃用的特征的警告
    E EnvironmentError 操作系统错误的基类
    EOFError 没有内建输入,到达EOF 标记
    Exception 常规错误的基类
    F FloatingPointError 浮点计算错误
    FutureWarning 关于构造将来语义会有改变的警告
    G GeneratorExit 生成器(generator)发生异常来通知退出
    I ImportError 导入模块/对象失败
    IndentationError 缩进错误
    IndexError 序列中没有没有此索引(index)【越界】
    IOError 输入/输出操作失败
    K KeyboardInterrupt 用户中断执行(通常是输入^C)
    KeyboardInterrupt 用户中断执行(通常是输入^C)
    KeyError 映射中没有这个键
    L LookupError 无效数据查询的基类
    M MemoryError 内存溢出错误(对于Python 解释器不是致命的)
    N NameError 未声明/初始化对象 (没有属性)
    NotImplementedError 尚未实现的方法
    O OSError 操作系统错误
    OverflowError 数值运算超出最大限制
    OverflowWarning 旧的关于自动提升为长整型(long)的警告
    P PendingDeprecationWarning 关于特性将会被废弃的警告
    R ReferenceError 弱引用(Weak reference)试图访问已经垃圾回收了的对象
    RuntimeError 一般的运行时错误
    RuntimeWarning 可疑的运行时行为(runtime behavior)的警告
    S StandardError 所有的内建标准异常的基类
    StopIteration 迭代器没有更多的值
    SyntaxError Python 语法错误
    SyntaxWarning 可疑的语法的警告
    SystemError 一般的解释器系统错误
    SystemExit 解释器请求退出
    SystemExit Python 解释器请求退出
    T TabError Tab 和空格混用
    TypeError 对类型无效的操作
    U UnboundLocalError 访问未初始化的本地变量
    UnicodeDecodeError Unicode 解码时的错误
    UnicodeEncodeError Unicode 编码时错误
    UnicodeError Unicode 相关的错误
    UnicodeTranslateError Unicode 转换时错误
    UserWarning 用户代码生成的警告
    V ValueError 传入无效的参数
    W Warning 警告的基类
    WindowsError 系统调用失败
    Z ZeroDivisionError 除(或取模)零 (所有数据类型)

    捕获异常

    python2.x

    try:
    	...some functions...
    except Exception, e:
    	print(e)
    

    python3.x

    try:
    	...some functions...
    except Exception as e:
    	print(e)
    

    常见错误举例

    NameError

    尝试访问一个未申明的变量

    >>> v
    NameError: name 'v' is not defined
    

    ZeroDivisionError

    • 除数为0 *
    >>> v = 1/0
    ZeroDivisionError: int division or modulo by zero
    

    SyntaxError

    语法错误

    int int
    SyntaxError: invalid syntax (<pyshell#14>, line 1)
    

    IndexError

    索引超出范围

    List = [2]
    >>> List[3]
    Traceback (most recent call last):
      File "<pyshell#18>", line 1, in <module>
        List[3]
    IndexError: list index out of range
    

    KeyError

    字典关键字不存在

    Dic = {'1':'yes', '2':'no'}
    >>> Dic['3']
    Traceback (most recent call last):
      File "<pyshell#20>", line 1, in <module>
        Dic['3']
    KeyError: '3'
    

    IOError

    输入输出错误

    >>> f = open('abc')
    IOError: [Errno 2] No such file or directory: 'abc'
    

    AttributeError

    访问未知对象属性

    >>> class Worker:
     def Work():
      print("I am working")
    
    >>> w = Worker()
    >>> w.a
    Traceback (most recent call last):
      File "<pyshell#51>", line 1, in <module>
        w.a
    AttributeError: 'Worker' object has no attribute 'a'
    

    ValueError

    数值错误

    >>> int('d')
    Traceback (most recent call last):
      File "<pyshell#54>", line 1, in <module>
        int('d')
    ValueError: invalid literal for int() with base 10: 'd'
    

    TypeError

    类型错误

    >>> iStr = '22'
    >>> iVal = 22
    >>> obj = iStr + iVal;
    Traceback (most recent call last):
      File "<pyshell#68>", line 1, in <module>
        obj = iStr + iVal;
    TypeError: Can't convert 'int' object to str implicitly
    

    AssertionError

    断言错误

    >>> assert 1 != 1
    Traceback (most recent call last):
      File "<pyshell#70>", line 1, in <module>
        assert 1 != 1
    AssertionError
    

    NotImplementedError

    方法没实现引起的异常

    class Base(object):
        def __init__(self):
            pass
    
        def action(self):
            #抛出异常,说明该接口方法未实现
            raise NotImplementedError
    

    LookupError

    键、值不存在引发的异常

    是IndexError、KeyError的基类, 如果你不确定数据类型是字典还是列表时,可以用LookupError捕获此异常

    StandardError

    标准异常

    除StopIteration, GeneratorExit, KeyboardInterrupt 和SystemExit外,其他异常都是StandarError的子类。

  • 相关阅读:
    c++跨平台技术学习(一)--使用公共的代码
    软件项目将死的27个征兆
    Java中的方法重载应用
    Java成员变量的初始化和在內存中的运行机制
    Java源文件结构和Java常用包
    细说Java访问控制符
    构造函数与this
    linux基础学习-6.3-DNS的配置文件
    linux基础学习-6.2-网卡配置文件
    linux基础学习-6.1-目录结构的特点
  • 原文地址:https://www.cnblogs.com/gmpy/p/12777242.html
Copyright © 2011-2022 走看看