python异常记录

打印出异常信息

BaseException后面定义 msg 变量用于接收异常信息,通过print 将其打印出来
try:

    open("abc.txt",'r')
    print aa
except BaseException,msg:
    print msg
打印结果:
>>> ================================ RESTART ================================
>>>

[Errno 2] No such file or directory: 'abc.txt'

Python中常见的异常:

异常 描述
BaseException 新的所有异常类的基类
Exception 所有异常类的基类,但继承 BaseException
AssertionError assert 语句失败
AttributeError 试图访问一个对象没有属性
IOError 输入输出异常,试图打一个不存的文件(包括其它情况)时引起
NameError 使用一个还未赋值对象的变量
IndexError 在使用序列中不存在的索引引发
IndentationError 语法错误,代码没有正确的对齐
KeyboardInterrupt Ctrl+C 被按下,程序被强行终止
TypeError 传入的对象类型与要求不符
SyntaxError 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 !



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值