新手学Python 第十篇 异常

来源:互联网 发布:餐饮数据图 编辑:程序博客网 时间:2024/06/08 16:24
异常是程序出现错误而在正常控制流以外采取的行动。


异常可以通过try语句来检测。任何在try语句块里的代码都会被监测,检查
有无异常发生。


try语句有两种主要形式:try-except 和 try-finally
两者的区别:
1、两个语句互斥,只能使用其中一种;
2、一个try语句可以对应一个或多个execpt子句,但只能对应一个finally子句
3、使用try-except可以检测盒处理异常,而try-finally只允许检测异常并进
   行必要的清理工作,没有异常处理措施。

try-except:
提示:try-except后可以加一个可选else子句,用于不发生异常时执行
>>> try:
     f = open('blah','r')
    except IOError,e:
        print 'could not open file:',e


在程序运行时,解释器执行完try块后如果没有发生异常,则执行流就会跳过
except语句继续执行。如果异常发生,try块中的剩余代码被跳过。


除程序错误触发异常外,程序员还可以使用raise语句 引发异常。使用raise

时还得指明错误/异常的名称和伴随异常触发的异常对象,引发的异常应该

是一个Error或Exception类的直接或间接导出类。

例如:

class ShortInputException(Exception):    def __init__(self,length,atleast):        Exception.__init__(self)        self.length = length        self.atleast = atleasttry:    s = raw_input('Enter something -->')    if len(s) <3:        raise ShortInputException(len(s),3)except EOFError:    print '\nWhy 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.'

try-finally:

可以用来保证无论异常是否发生,finally块的程序都能够执行

import timetry:    f = file('D:\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'