python异常记录
来源:互联网 发布:破解三星s4支持4g网络 编辑:程序博客网 时间:2024/06/03 14:53
打印出异常信息
在 BaseException后面定义msg 变量用于接收异常信息,通过print将其打印出来
try:
print aa
except BaseException,msg:
print msg
打印结果:
>>> ================================ RESTART ================================
>>>
[Errno 2] No such file or directory: 'abc.txt'
Python中常见的异常:
try...except 与 else配合使用
try:
aa = '异常测试'
print aa
except Exception,msg:
print msg
else:
print '没有异常!'
打印结果:
>>> ================================ RESTART ================================
>>>
异常测试
没有异常!
说明:else 语句只有在没有异常的情况下才会被执行,但是有些情况下不管是否出现异常这些操作都能被执行,比如文
件的关闭,锁的释放,把数据库连接返还给连接池等操作。
Try...finally...语句---均会执行finally语句
首先我们来创建一个 poem.txt 文件。
pome.txt
abc
efg
hijk
lmn
opq
下面我们通过一个小程序来读取文件中的内容。
import time
files = file("poem.txt",'r')
strs = files.readlines()
try:
for l in strs:
print l
time.sleep(1)
finally:
files.close()
print 'Cleaning up ...closed the file'
第一次正常执行:
打印结果:
>>> ================================ RESTART ================================
>>>
abc
efg
hijk
lmn
opq
Cleaning up ...closed the file
第二次按下ctrl+c终止执行:
打印结果:
>>> ================================ RESTART ================================
>>>
abc
efg
Cleaning up ...closed the file
Traceback (most recent call last):
File "F:\project\count.py", line 8, in <module>
time.sleep(1)
KeyboardInterrupt
抛出异常--- raise只能使用Python 中所提供的异常类,自定义的异常类不起作用
对于 print 方法来说只能打印错误信息,Python中提供raise 方法来抛出一个异常
filename = raw_input('please input file name:')
if filename=='hello':
raise NameError('input file name error !')
运行结果:
>>> ================================ RESTART ================================
>>>
please input file name:hello
Traceback (most recent call last):
File "F:\project\count.py", line 5, in <module>
raise IOError('input file name error !')
NameError: input file name error !
- python异常记录
- python异常记录
- Python 异常错误记录
- python logging 记录异常信息
- python日志记录完整的异常信息traceback stack
- python错误处理记录完整的异常堆栈信息
- 异常记录
- 异常记录
- 异常记录
- 异常记录
- 异常记录
- 异常记录
- 异常记录
- 异常记录
- Python 异常
- python 异常
- python 异常
- python异常
- 自动行为操控Steering(九)—徘徊(单体操控)
- 【CodeForces 626E】Simple Skewness (三分)
- 大学英语单词L
- UNP
- 欢迎大家走进我的园子 目录整理篇
- python异常记录
- ggplot2之Layer—— geoms(三)
- 二分查找--bisect
- MFC picture 图像清空
- 冒泡排序和简单选择排序实现
- docker安装redis
- 剑指Offer—61—序列号二叉树
- select @@identity的用法
- java编程规范