python学习笔记——8_异常

#coding:UTF-8
#try.. except 开始

'''
我们把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。
except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。
如果没有给出错误或异常的名称,它会处理 所有的 错误和异常。
对于每个try从句,至少都有一个相关联的except从句。

如果某个错误或异常没有被处理,默认的Python处理器就会被调用。
它会终止程序的运行,并且打印一个消息,我们已经看到了这样的处理。

你还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。

'''
import sys

try:
    s=raw_input("Enter something -->")
except EOFError: #ctrl+d 测试
    print 'Why did you do an EOF on me?'
    sys.exit()
except:
    print'some error/exception occurred.'
print 'Done!'
#try.. except 结束

#============================

#引发异常 开始

class ShortInputException(Exception):
    def __init__(self,length,atleast):
        Exception.__init__(self)
        self.length=length
        self.atleast=atleast
try:
    s=raw_input('Enter something-->')
    if len(s)<3:
        raise ShortInputException(len(s),3)
except EOFError:
    print 'Why did you do an EOF on me?'
except ShortInputException,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 --> # ctrl+d
Why did you do an EOF on me?

Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3

Enter something --> abc
No exception was raised.
'''

#引发异常 结束

#=====================================

#try..finally 开始

'''
在一个try块下,你可以同时使用except从句和finally块。
如果你要同时使用它们的话,需要把一个嵌入另外一个。
'''


import time
try:
    f=file('poem.txt')
    while True:
        line=f.readline()
        if len(line)==0:
            break;
        time.sleep(2)
        print line,
finally:
    f.close()
    print 'Cleaning up... closed the file'

'''
结果
Programming is fun
Cleaning up... closed the file

Traceback (most recent call last):
  File "E:\python_test\8_异常.py", line 74, in <module>
    time.sleep(2)
KeyboardInterrupt
'''

'''
在程序运行的时候,按Ctrl-c中断/取消程序。
我们可以观察到KeyboardInterrupt异常被触发,程序退出。
但是在程序退出之前,finally从句仍然被执行,把文件关闭
'''
#try..finally 结束

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值