zoukankan      html  css  js  c++  java
  • 学习九-python 异常处理

    所谓的异常简单来讲就是程序出现逻辑错误或者用户不合法的输入。常见的比如一个列表索引超出了列表的索引范围,打开一个文件时文件名输入错误系统找不到文件等等。

    常见的异常

    AssertionError: 断言(assert)语句失败

    当assert关键字后面的条件不为真使,程序就会抛出AssertionError异常。
    看一个例子:

    >>> mylist = ["python"]
    >>> assert len(mylist)>0
    >>> mylist.pop()
    'python'
    >>> assert len(mylist)>0
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        assert len(mylist)>0
    AssertionError
    >>> mylist
    []

    使用内置函数pop()将列表中的元素弹出后,该元素将不再在列表中。

    AttributeError:表示访问未知的对象属性

    >>> mylist = ["python"]
    >>> mylist.java
    Traceback (most recent call last):
      File "<pyshell#10>", line 1, in <module>
        mylist.java
    AttributeError: 'list' object has no attribute 'java'

    由于j’ava对象不存在,所以会抛出异常。

    IndexError :索引超出序列的范围

    >>> examplelist = ['a','b' ,'c']
    >>> examplelist
    ['a', 'b', 'c']
    >>> examplelist[3]
    Traceback (most recent call last):
      File "<pyshell#13>", line 1, in <module>
        examplelist[3]
    IndexError: list index out of range
    >>> 

    KeyError:字典中查获找一个不存在的键

    >>> exampledict = {"a":1,"b":2,"c":3}
    >>> exampledict
    {'a': 1, 'b': 2, 'c': 3}
    >>> exampledict["a"]
    1
    >>> exampledict["d"]
    Traceback (most recent call last):
      File "<pyshell#19>", line 1, in <module>
        exampledict["d"]
    KeyError: 'd'

    字典中键“d”不存在,索引不到,抛出异常。

    NameError:尝试访问一个不存在的变量

    >>> examplelist = ['a','b' ,'c']
    >>> examplelist
    ['a', 'b', 'c']
    >>> alist
    Traceback (most recent call last):
      File "<pyshell#21>", line 1, in <module>
        alist
    NameError: name 'alist' is not defined

    由于直接访问的变量 alist并没有像变量 examplelist 那样先定义就访问了,这个变量是不存在的,所以抛出异常。

    OSError: 操作系统产生的异常

    打开一个不存在的文件就会抛出FileNotFoundError异常,该异常属于OSError的一个子类。

    >>> fname = input("input a file name:")
    input a file name:example.txt
    >>> f=open(fname,'r')
    Traceback (most recent call last):
      File "<pyshell#24>", line 1, in <module>
        f=open(fname,'r')
    FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'

    SyntaxError: 语法错误

    初学者见得最多的错误吧。比如在定义一个字典时写成下面的样子:

    exampledict = {"a"=1,"b"=2,"c"=3}
    SyntaxError: invalid syntax

    python没有这样的语法。字典其中一种定义方式应该这样的 exampledict = {“a”:1,”b”:2,”c”:3}

    TypeError:不同类型间的无效操作

    这种错误常发生在计算或者复制中。如下一个整形和一个字符的相加操作。

    >>> examplelist = ['a','b','c']
    >>> exampledict = {"a":1,"b":2,"c":3}
    >>> examplelist[1]+exampledict["a"]
    Traceback (most recent call last):
      File "<pyshell#27>", line 1, in <module>
        examplelist[1]+exampledict["a"]
    TypeError: must be str, not int

    还有很多这里不一一举例

    遇到异常时不要慌,问题总是能解决的。

    异常的捕获

    try-except

    try:
        需要检测的程序段
    except Exception [as reason]:
        异常处理方法

    可以在一个try后面跟着多个except说不同的异常经行处理。

    try:
        需要检测的程序段
    except TypeError as reason:
        异常处理方法1
    except TypeError as reason:
        异常处理方法2

    捕获所有异常:

    try:
        需要检测的程序段
    except:
        异常处理方法

    try-finally

    使用finally给用户有挽回的余地,如果出现异常,则会想执行except中的异常处理,接着到finally中的处理。如果没有运行异常,则直接到finally中处理。比如你打开了一个文件,但是你关闭之前的其他操作造成了异常,那么程序将直接跳到except中处理异常了,那文件没有关闭怎么办,这时finally就起作用了。但except中异常处理完之后,接着就是到finally中进行异常处理,finally中的异常处理一定会被执行的。

    try:
        需要检测的程序段
    except:
        异常处理方法
    finally:
        异常处理方法

    with语句

    with语句会自动帮助关闭打开的文件。
    这里直接摘取自小甲鱼的书中的代码:

    try:
        f = open('data.txt','w')
        for each_line in f:
            print(each_line)
    except OSError as reason:
                print('error:'+str(reason))
    finally:
        f.close()
    try:
        with open('data.txt','w') as f:
        for each_line in f:
            print(each_line)
    except OSError as reason:
                print('error:'+str(reason))

    制造异常并抛出 raise语句

    >>> raise TypeError
    Traceback (most recent call last):
      File "<pyshell#28>", line 1, in <module>
        raise TypeError
    TypeError
    >>> raise TypeError("还能带参数对你抛出异常做更详细的解释")
    Traceback (most recent call last):
      File "<pyshell#29>", line 1, in <module>
        raise TypeError("还能带参数对你抛出异常做更详细的解释")
    TypeError: 还能带参数对你抛出异常做更详细的解释

    这是学习笔记,不是只是“看起来认真”,就在这里做一些记录,参考 小甲鱼,清华出版社《零基础入门学习Python》。

  • 相关阅读:
    pcntl_fork 导致 MySQL server has gone away 解决方案
    视频网站 阻止迅雷劫持下载
    推荐大家使用的CSS书写规范、顺序
    console对象
    js Math函数
    致13级师弟师妹关于校招的一些话
    UVA514 铁轨 Rails:题解
    SP1805 HISTOGRA
    洛谷 P4363 [九省联考2018]一双木棋chess 题解
    比赛:大奔的方案solution
  • 原文地址:https://www.cnblogs.com/siucaan/p/9623226.html
Copyright © 2011-2022 走看看