【Python】异常

来源:互联网 发布:windows 7旗舰 编辑:程序博客网 时间:2024/05/16 18:32

Python的异常体系分为两种,一种是捕获已有的由Python或程序本身引发的异常,try\except\else

try...except...else...finally

执行try下的语句,如果引发异常,则会跳到except语句,对每个except分支顺序执行,如果符合except中的异常,就执行相应语句。如果所有except都不符合异常,会转入下一个调用本代码的高层try代码中。

如果try下的语句正常执行,则执行else代码。无论何种情况都会执行finally代码。

二种是主动触发一个异常,raise\

class MyInputException(Exception):    ''' a user-defined exception class'''    def __init__(self, length, atLeast):        Exception.__init__(self)        self.length = length #self.length 实例的length域,相当于成员变量        self.atLeast = atLeasttry:    text = input("Enter something: ")    if len(text) < 3:        raise MyInputException(len(text), 3)except EOFError:    print("an EOF error!")except MyInputException as ex: #ex是MyInputException的一个对象    print('''MyInputException The input was {} long, it should be          at least {} long'''.format(ex.length, ex.atLeast))except KeyboardInterrupt:    print("Keyboard Interrupt!")else:    print("you entered {0}".format(text))

在except 从句中,我们提供了错误类和用来表示错误/异常对象的变量。这与函数调用中的形参和实参概念类似。

分别输入ctrl + C,  ctrl + D, d:
>>> ================================ RESTART ================================>>> Enter something: Keyboard Interrupt!>>> ================================ RESTART ================================>>> Enter something: an EOF error!>>> ================================ RESTART ================================>>> Enter something: dMyInputException The input was 1 long, it should be          at least 3 long


如果希望无论是否发生错误都关闭文件,可以使用finally语句块:

import timetry:    f = open("C:\\Users\\new.txt")  #默认为只读方式打开    while True: #usual file-reading idiom        line = f.readline()        if len(line) == 0:            break        print(line, end = '')        time.sleep(2) #to make sure it runs for a whileexcept KeyboardInterrupt:    print('!! You cancelled the reading from the file.')finally:    f.close()    print('(Cleaing up: closing the file.)')


with语句也能完成try块中获取资源,finally中释放资源的工作

0 0
原创粉丝点击