[python学习]异常
来源:互联网 发布:国考面试报网络培训班 编辑:程序博客网 时间:2024/06/09 20:06
try except
代码:
#!/usr/bin/python# Filename: raising.py# Python version: 3.4.3class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleasttry: s = input('Enter something --> ') if len(s) < 3: raise ShortInputException(len(s), 3) # Other work can continue as usual hereexcept EOFError: print ('\nWhy did you do an EOF on me?')except ShortInputException as x: print ('ShortInputException: The input was of length %d, \ was expecting at least %d' % (x.length, x.atleast))else: print ('No exception was raised.')
结果:
>>> Enter something --> 2ShortInputException: The input was of length 1, was expecting at least 3>>>
try finally
代码:
#!/usr/bin/python# Filename: finally.pyimport timetry: f = open('poem.txt') while True: # our usual file-reading idiom line = f.readline() if len(line) == 0: break time.sleep(2) print (line,end='')finally: f.close() print ('Cleaning up...closed the file')
结果:
在运行过程中按control + c中断程序,会执行finally中代码,关闭文件。
>>> Cleaning up...closed the fileTraceback (most recent call last): File "/Users/junyu92-mbpr/Desktop/Learn/python/简明教程/finally.py", line 12, in <module> time.sleep(2)KeyboardInterrupt>>>
0 0
- Python学习笔记:异常
- python学习之异常
- python学习-异常
- 学习python(五) 异常
- Python学习之异常
- python学习之异常
- [python学习]异常
- Python学习之异常
- python学习--异常
- Python学习之异常
- Python学习笔记-异常
- Python学习异常检测
- Python学习--异常处理,自定义异常类
- Python学习笔记--异常处理
- python 学习笔记8-----异常
- python学习之异常处理
- Python学习笔记--异常处理
- Python学习笔记--异常处理
- 我的列表
- Linux中查看CPU信息
- ssh整合action中获取service为空解决方案
- BNU --- LiuLibo's Party
- 单链表的创建、销毁与K结点处插入新结点
- [python学习]异常
- hihoCoder 1075 开锁魔法III (dp,划分阶段)
- BT协议的详细分析
- 例题6-8 树 UVa548
- BCB中一些常用函数
- 【猫猫的Unity Shader之旅】之UV动画
- Python 环境搭建
- 最详细的JavaScript和事件解读
- printf非常奇怪的参数问题