1. try...except
与java类似,把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。
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
还可以让try..catch
块关联上一个else
从句。当没有异常发生的时候,else
从句将被执行。
2.引发异常
你可以使用raise
语句 引发 异常,与java中的throw 类似。引发的错误或异常应该分别是一个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
)
except
ShortInputException, x:
print
'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
3.finally
假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,这可以使用finally
块来完成。
try
:
f = file
(
'poem.txt'
)
finally
:
f.close()
print
'Cleaning up...closed the file'