zoukankan      html  css  js  c++  java
  • Python基础(10)

    Python

    异常:程序出现了错误而在正常控制流以外采取的行为

    Python中常见的异常:

    1. NameError:尝试访问一个未声明的变量

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

    2. SyntaxError:解释器语法错误,是唯一不在运行时发生的异常

    >>> for
      File "<stdin>", line 1
        for
          ^
    SyntaxError: invalid syntax

    3. IndexError:超出范围的值索引序列

    >>> lst = []
    >>> lst[1]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range
    try-except

    定义了进行异常监控的一段代码,并提供了处理异常的机制

    try:

       try_suite #监控异常

    except Exception[,reason]:

        except_suite #异常处理代码

    >>> try:
    ...     f = open('somefile','r')
    ... except IOError,e:
    ...     print 'could not open file:',e
    ...
    could not open file: [Errno 2] No such file or directory: 'somefile'
    >>>

    上例中,只捕获了IOError异常,任何其它异常不会被捕获。

    可以检测多种异常:

    try:

       try_suite #监控这里的异常

    except Exception1[,reason1]:

        except_suite1 #异常处理代码

    except Exception2[,reason2]:

        except_suite2 #异常处理代码

    >>> def safe_float(obj):
    ...     try:
    ...         retval = float(obj)
    ...     except ValueError:
    ...         retval = 'could not convert non-number to float'
    ...     except TypeError:
    ...         retval = 'object type cannot be converted to float'
    ...     return retval
    ...
    >>> safe_float('xy.z')
    'could not convert non-number to float'
    >>> safe_float([1,2])
    'object type cannot be converted to float'
    >>>

    一个except语句可以检测多种异常,多个异常要放在一个元组中:

    try:

       try_suite #监控这里的异常

    except (Exception1 [,Exception2 [, …ExceptionN]]) [,reason]:

        except_suite #异常处理代码

    >>> def safe_float(obj):
    ...     try:
    ...         retval = float(obj)
    ...     except (ValueError,TypeError):
    ...         retval = 'could not convert to float'
    ...     return retval
    ...
    >>> safe_float('xy.z')
    'could not convert to float'
    >>> safe_float([1,2])
    'could not convert to float'

    一个except语句可以检测多种异常,多个异常要放在一个元组中:

    try:

       try_suite #监控这里的异常

    except Exception,e:

        except_suite #异常处理代码

    Exception是大部分异常类的基类,因此上述代码支持捕获大多异常。KeyboardInterrupt(用户中断执行Ctrl+C)和SystemExit(python解释器请求退出)不是由于代码错误条件引起的异常,如下为异常类的树:

    -BaseException

      |- KeyboardInterrupt

      |- SystemExit

      |- Exception

         |-所有内建异常

    try-except的作用是提供一个可以提示错误或处理错误的机制,而不是一个错误过滤器,下面这种捕获所有异常并忽略错误不是一种合理的编程方式:

    try:

        …

    except: Exception:

       pass

    避免把大片代码装入try-except中然后使用pass忽略掉错误。

    可以捕获特定的异常并忽略它们,或是捕获所有的异常并采取特定的动作。

     
    v异常参数:

    异常也可以有参数,标准内建异常提供至少一个参数,指示异常原因的一个字符串

    异常参数自身会组成一个元组,并存储为异常类的实例。

    对于大多数内建异常,也就是从StandardError派生的异常,这个元组中只包含一个指示错误原因的字符串。操作系统或其他环境类型的错误,例如:IOError,元组中会把操作系统的错误编号放到错误字符串的前面

    >>> try:
    ...     float('xyz')
    ... except Exception,e:
    ...     pass
    ...
    >>> e
    ValueError('could not convert string to float: xyz',)
    >>> type(e)
    <type 'exceptions.ValueError'>
    >>> isinstance(e, ValueError)
    True
    >>> isinstance(e, Exception)
    True
    vtry-finally

    try:

        try-suite

    finally:

        finally-suite #无论如何都执行

    finally子句是无论异常是否发生,是否捕获都会执行的一段代码

    当在try范围中产生一个异常时,会立即跳转到finally语句段,当finally中的所有代码都执行完毕后,会继续向上一层引发异常。

    如果finally中的代码引发了另一个异常或由于return、break、continue语法而终止,原来的异常将丢失而且无法重新引发。

    try-except-else-finally

    在try语句块中所有代码都执行成功后,将会执行else子句。

    try:

        try_suite

    except Exception1:

        suite_for_exception1

    except (Exception2,Exception3,Exception4):

        suite_for_exception2_and_3_and_4

    except (Exception6, Exception7), Argument67:

        suite_for_Exception6_and_7_plus_argument

    except:

        suite_for_all_other_exceptions

    finally:

        always_execute_suite

    无论你选择哪一种语法,至少要有一个except子句

    try语句块中异常发生点后的剩余语句将被忽略,不会被执行,解释器将搜索处理器,一旦找到,就开始执行处理器中的代码。如果没有找到合适的处理器,那么异常就向上移交给调用者去处理,如果上层调用者也没有找到合适的处理器,则该异常会继续被向上移交,直到找到合适的处理器,如果到达最顶层仍然没有找到对应处理器,那么就认为该异常未处理,解释器会显示出跟踪记录,然后退出。

    之前看到的异常都是由解释器触发的。程序员也可以在遇到错误时主动触发异常:

    raise [SomeException, [args [, traceback]]]

    SomeException:可以是异常类或实例,如果是一个实例,则不能再带args参数

    args: 异常参数

    traceback: 跟踪记录对象

    >>> class MyException(Exception):
    ...     def __init__(self, length, atleast):
    ...         Exception.__init__(self)
    ...         self.length = length
    ...         self.atleast = atleast
    ...     def __str__(self):
    ...         return 'MyException occered, length:%s, atleast:%s'%(self.length,self.atleast)
    ...
    >>> try:
    ...     raise MyException(2,3)
    ... except MyException,e:
    ...     print e
    ...
    MyException occered, length:2, atleast:3

    sys模块中的exc_info()函数,是另一种获取异常信息的途径,它提供了一个三元祖信息,比我们单纯用异常参数获取的信息多

    >>> exc_tuple
    (<type 'exceptions.ValueError'>, ValueError('could not convert string to float: xy.z',), <traceback object at
    0x01C0DF08>)

    从sys.exc_info()得到的元组为:

    exc_type: 异常类

    exc_value:异常类的实例

    exc_traceback: 跟踪记录对象

    断言是一句等价于布尔真的判定,如果表达式为假,触发AssertionError异常

    assert expression[, arguments]

    >>> assert 1==1
    >>> assert 1==0
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError
    >>> assert 1==0, 'one does not equal zero'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError: one does not equal zero

    用try-except可以捕获AssertionError异常:

    >>> try:
    ...     assert 1==0 , 'one does not equal zero'
    ... except AssertionError,e:
    ...     print '%s:%s'%(e.__class__.__name__,e)
    ...
    AssertionError:one does not equal zero
    >>>
  • 相关阅读:
    Codeforces 177G2 Fibonacci Strings KMP 矩阵
    Codeforces Gym100187C Very Spacious Office 贪心 堆
    Codeforces 980F Cactus to Tree 仙人掌 Tarjan 树形dp 单调队列
    AtCoder SoundHound Inc. Programming Contest 2018 E + Graph (soundhound2018_summer_qual_e)
    BZOJ3622 已经没有什么好害怕的了 动态规划 容斥原理 组合数学
    NOIP2016提高组Day1T2 天天爱跑步 树链剖分 LCA 倍增 差分
    Codeforces 555C Case of Chocolate 其他
    NOIP2017提高组Day2T3 列队 洛谷P3960 线段树
    NOIP2017提高组Day2T2 宝藏 洛谷P3959 状压dp
    NOIP2017提高组Day1T3 逛公园 洛谷P3953 Tarjan 强连通缩点 SPFA 动态规划 最短路 拓扑序
  • 原文地址:https://www.cnblogs.com/TonyZhao/p/3530944.html
Copyright © 2011-2022 走看看