#-*- coding=utf-8-*-
#try..except
import sys
try:
s = raw_input('Enter something -->')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
else:
print 'No error/exception occurred.'
print 'Done'
'''
summary:
使用try..except语句来处理异常:
把通常的语句放在try块中,而把我们的错误处理语句放在except块中
1)把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。
2)except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有给出错误或异常的名称,它会处理 所有的 错误和异常。
3)每个try从句,都至少有一个相关联的except从句。
4)如果某个错误或异常没有被处理,默认的Python处理器就会被调用。它会终止程序的运行,并且打印一个消息,我们已经看到了这样的处理。
5)还可以让try..except块关联上一个else从句。当没有异常发生的时候,else从句将被执行。
6)我们还可以得到异常对象,从而获取更多有个这个异常的信息。
'''
'''如何创建自己的异常类型和如何引发异常'''
#引发异常:
# raise语句
# 1)要指明错误/异常的名称,和伴随异常触发的异常对象
# 2)可以引发的错误或异常,应该分别是Error或Exception类的一个直接或间接导出类
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) #实例的创建方法,为什么不用调__init__///??
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
'''提供了错误类和用来表示错误/异常对象的变量
使用异常对象x来捕获异常中的信息,如果为自定义异常,那么x就是异常ShortInputException的实例
使用“x.属性名”访问异常信息(length和atleast域)'''
print 'ShortInputException: The input was of length %d, was expecting at least %d' % (x.length, x.atLeast)
else:
print 'No exception was raised.'
#finally:
# sys.exit() #避免程序直接输入Ctrl+C时爆出KeyboardInterrupt异常
#
'''###
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.'
#
'''
输出Output:
Programming is fun
When the work is done
Cleaning up...closed the file.
Traceback (most recent call last):
File "ch13_exception.py", line 81, in <module>
time.sleep(2)
KeyboardInterrupt
'''