简明python教程:异常


try..except

通常的语句放在try-块中,

而把错误处理语句放在except-块中。

import sys
try:
s=raw_input('Enter something---->')
except EOFError:
print '\n why did you do an eof on me'
sys.exit()
except:
print '\n some error/exception occurred.'
print 'done'

引发异常

使用raise语句 引发 异常.

指明错误/异常的名称和伴随异常 触发的 异常对象

引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类。

class ShortInputException(Exception):
'''a user-defined exception class'''
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)
    #other work can continue as usual here
except EOFError:
print 'why did you do an eof on me'
except ShortInputException,x:
print 'ShortInputException:the input was of length %d,\
was excepting at least %d '%(x.length,x.atleast)
else:
print 'no error!'

try..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....'

转载于:https://www.cnblogs.com/chenjz1993/p/7017123.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值