《Python基础教程(第二版)》学习笔记 -> 第八章 异常

什么是异常


   Python用 异常对象(exception object)来表示异常情况。遇到错误后,会引发异常,如果异常对象并未被处理或者捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行:

 

>>> 1/0



Traceback (most recent call last):

  File "<pyshell#0>", line 1, in <module>

    1/0

ZeroDivisionError: integer division or modulo by zero

  每个异常都是一些类的实例,这些实例可以被引发,并且可以用很多种方法进行捕捉,是的程序可以捕捉错误并且对其进行处理,而不是让整个程序失败。

  

按自己的方式出错


  1.  raise 语句
    为了引发异常,可以使用一个类(应该是Exception的子类)或者实例参数调用raise语句。使用类时,程序会自动创建实例,下面是一些例子:
    >>> raise Exception
    
    
    
    Traceback (most recent call last):
    
      File "<pyshell#0>", line 1, in <module>
    
        raise Exception
    
    Exception

    下面是一些最重要的内建异常类:

    类名

    描述

    Exception   所有异常的基类  
    AttributeError   特性引用或者赋值失败时引发
    IOError   试图打开不存在的文件(包括其他情况)时引发
    IndexError 在使用序列中不存在的索引时引发
    KeyError 在使用映射中不存在的键时引发
    NameError 在找不到名字(变量)时引发
    SyntaxError 在代码为错误形式时引发
    TypeError 在内建操作或者函数应用于错误类型的对象时引发
    ValueError 在内建操作或者函数应用于正确类型的对象,但是该对象使用不合适的值时引发    
    ZeroDivisionError     在除法或者模除操作的第二个参数为0的时候引发

     













  2. 自定义异常类
    确保从Exception类继承:
    >>> class SomeCustomException(Exception):pass

     

  3. 捕捉异常
    先举例:
    try:
    
        x = input('Enter the first number:')
    
        y = input('Enter the second number:')
    
        print x/y
    
    except ZeroDivisionError:
    
        print "The second number can't be zero!"

    运行结果:

    >>> 
    
    Enter the first number:3
    
    Enter the second number:0
    
    The second number can't be zero!

     

  4. 不止一个except子句
    try:
    
        x = input('Enter the first number:')
    
        y = input('Enter the second number:')
    
        print x/y
    
    except ZeroDivisionError:
    
        print "The second number can't be zero!"
    
    except TypeError:
    
        print "That wasn't a number , was it?"

    运行结果:

    Enter the first number:2
    
    Enter the second number:"python"
    
    That wasn't a number , was it?

    只要在try/except后面追加一个except语句

  5. 用一个块捕捉两个异常
    try:
    
        x = input('Enter the first number:')
    
        y = input('Enter the second number:')
    
        print x/y
    
    except (ZeroDivisionError,TypeError,NameError):
    
        print "Your number were bogus..."

     

  6. 捕捉对象
    先举例运行:
    try:
    
        x = input("Enter the first number:")
    
        y = input("Enter the second number:")
    
        print x/y
    
    except(ZeroDivisionError,TypeError),e:
    
        print e

    运行结果:

    Enter the first number:3
    
    Enter the second number:0
    
    integer division or modulo by zero

    如果希望在except子句中访问异常对象本身,可以使用两个参数。比如,如果想让程序继续运行,但是又因为某种原因想记录下错误,这个功能就很实用。

  7. 万事大吉
    对try/except加入else语句
    示例:
    while True:
    
        try:
    
            x = input("Enter the First number: ")
    
            y = input("Enter the Second number: ")
    
            value = x/y
    
            print "x/y is ", value
    
        except Exception,e:
    
            print 'Invalid input:',e
    
            print 'PLS try again!'
    
        else:
    
            break

    运行结果:

    Enter the First number: w
    
    Invalid input: name 'w' is not defined
    
    PLS try again!
    
    Enter the First number: 1
    
    Enter the Second number: 0
    
    Invalid input: integer division or modulo by zero
    
    PLS try again!
    
    Enter the First number: 5
    
    Enter the Second number: 4
    
    x/y is  1

     

异常和函数


   异常和函数能很自然地一起工作,如果异常在函数内引发而不被处理,它就会传播至函数调用的地方。如果在哪里也没有处理异常,它就会继续传播,一直到达主程序(全局作用域)。如果哪里没有异常处理程序,程序会带着堆栈跟踪中止。

  

 

你可能感兴趣的:(python)