美文网首页
Python的异常

Python的异常

作者: 上发条的树 | 来源:发表于2016-05-26 12:23 被阅读21次

    常见异常

    异常 描述
    NameError 尝试访问一个没有申明的变量
    ZeroDivisionError 除数为0
    SyntaxError 语法错误
    IndexError 索引超出序列范围
    KeyError 请求一个不存在的字典关键字
    IOError 输入输出错误(例如要读取的文件不存在 )
    AttributeError 尝试访问位置的对象属性

    简单介绍下

    NameError

    wxx
    变量没有初始化,即没有赋值。因为变量相当于一个标签,要将其贴到对象上才有意义。

    >>> wxx
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'wxx' is not defined
    

    ZeroDivisionError

    除数为0

    >>> 1/0
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: integer division or modulo by zero
    

    SyntaxError

    语法错误,编译时无法正确转化为Python字节码,故报错,只有修改正确之后才能编译成功。

    >>> def func()
      File "<stdin>", line 1
        def func()
                 ^
    SyntaxError: invalid syntax
    

    IndexError

    索引超过范围。这个道理告诉我们充大头鬼需要付出代价。

    >>> range(10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> f = range(10)
    >>> f[11]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range
    
    

    KeyError

    如果字典中不存在该关键字,报错。纯属无中生有了。

    >>> dic = {'name':'wxx','age':'23'}
    >>> dic['height']
    Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
    KeyError: 'height'
    

    IOError

    文件不存在。怎么可能有这个文件。

    >>> file = open("nvyou.avi")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IOError: [Errno 2] No such file or directory: 'nvyou.avi'
    

    AttributeError

    属性不存在,纯属无中生有。

    >>> def func():
    ...     a = 1
    ... 
    >>> fu = func()
    >>> fu.b
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'b'
    

    相关文章

      网友评论

          本文标题:Python的异常

          本文链接:https://www.haomeiwen.com/subject/pcqxdttx.html