zoukankan      html  css  js  c++  java
  • 简明python教程九----异常

    使用try...except语句来处理异常。我们把通常的语句放在try-块中,而把错误处理语句放在except-块中。

    import sys
    
    try:
        s = raw_input('Enter something-->')
    except EOFError:
        print '
    Why did you do an EOF on me?'
        sys.exit()
    except:
        print'
    Some error/exception occurred.'
    
    print 'Done'

    结果:

    ==================== RESTART: D:/python_test/pickling.py ====================
    Enter something-->
    
    Why did you do an EOF on me?
    >>> 
    ==================== RESTART: D:/python_test/pickling.py ====================
    Enter something-->
    Done

    把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。

    except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。

    如果没有给出错误或者异常的名称,它会处理所有的错误和异常。

    对于每个try从句,至少都有一个相关联的except从句。

    如果某个错误或异常没有被处理,默认的python处理器就会被调用。它会终止程序的运行,并且打印一个消息。

    还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。

    引发异常:

    可以使用raise语句引发异常,你需要指明错误/异常的名称和伴随异常触发的异常对象。你可以引发的错误和异常应该分别是一个Error或Exception类的直接或间接导出类。

    class ShortInputException(Exception):
        'A user-defined exception class.'
        def __init__(self,length,atleast):
            Exception.__init__(self)
            self.length=length
            self.atleast=atleast
    
    try:
        s=raw_input('Enter something-->')
        if len(s)<3:
            raise ShortInputException(len(s),3)
    except EOFError:
        print '
    Why did you do an EOF on me?'
    except ShortInputException,x:
        print 'ShortInputException: The input was of length %d,
            was expecting at least %d'%(x.length,x.atleast)
    else:
        print 'No exception was raised.'

    结果:

    ==================== RESTART: D:/python_test/pickling.py ====================
    Enter something-->
    
    Why did you do an EOF on me?
    >>> 
    ==================== RESTART: D:/python_test/pickling.py ====================
    Enter something-->ab
    ShortInputException: The input was of length 2,        was expecting at least 3
    >>> 
    ==================== RESTART: D:/python_test/pickling.py ====================
    Enter something-->abc
    No exception was raised.

    try...finally

    假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件。我们可以使用finally块来完成。

    注意,在一个try块下,你可以同时使用except从句和finally块,同时使用它们的时候,需要把一个嵌入另一个中

    import time
    try:
        f=file('poem.txt')
        while True:
            line = f.readline()
            if len(line)==0:
                break
            time.sleep(2)
            print line,
    finally:
        f.close()
        print 'Cleaning up...closed the file'

    结果:

    programming is fun
    When the work is done
    if you wanna make your work also fun:
    use Python!
    Cleaning up...closed the file

    说明:在每打印一行之前用time.sleep方法暂停2秒。程序在运行过程中,按Ctrl-c中断/取消程序。

    我们可以回看到这样:

    programming is fun
    When the work is done
    Cleaning up...closed the file
    
    Traceback (most recent call last):
      File "D:/python_test/pickling.py", line 64, in <module>
        time.sleep(2)
    KeyboardInterrupt
    

      KeyboardInterrupt异常被触发,程序退出。但在程序退出之前,finally从句仍然被执行,把文件关闭

  • 相关阅读:
    滑雪(dp好题)
    田忌赛马
    反质数(Antiprimes)
    LCA-倍增法(在线)
    二模 (2) day2
    Spring Integration
    [转载] Spring MVC
    收藏夹
    Linux profile File
    git merge 与 rebase 的区别
  • 原文地址:https://www.cnblogs.com/Caden-liu8888/p/6428757.html
Copyright © 2011-2022 走看看