【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 从句中,我们提供了错误类和用来表示错误/异常对象的变量。这与函数调用中的形参和实参概念类似。
>>> ================================ 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
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
- Python 异常
- python 异常
- python 异常
- python异常
- 【Python】异常
- python异常
- python异常
- python异常
- PYTHON-异常
- python异常
- Python 异常
- Python异常
- Python异常
- Python异常
- Python异常
- python 异常
- python 异常
- Python 异常
- 小递归
- javascript页面判断标题是否为空
- QProcess机制分析
- 第一个项目全过程
- Nginx配置文件nginx.conf中文详解(总结)
- 【Python】异常
- jlink v8 重新烧录解决不识别usb,灯不亮的问题
- 无法定位序数 xxxx 与动态链接库 avcodec-55.dll上
- Unable to instantiate fragment 的解
- RestEasy开发WebService一
- QProcess学习
- android 按HOME键后,再点击快捷图标,重新启动的问题
- dfs.client.file-block-storage-locations.timeout.millis引发的错误
- 不同文件的类成员变量的访问