你可以使用raise語句 引發(fā) 異常。你還得指明錯誤/異常的名稱和伴隨異常 觸發(fā)的 異常對象。你
可以引發(fā)的錯誤或異常應(yīng)該分別是一個Error或Exception類的直接或間接導(dǎo)出類。
#!/usr/bin/python
# Filename: raising.py
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 '\nWhy 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.'
輸出
$ python raising.py
Enter something -->
Why did you do an EOF on me?
$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3
$ python raising.py
Enter something --> abc
No exception was raised.
它如何工作這里,我們創(chuàng)建了我們自己的異常類型,其實(shí)我們可以使用任何預(yù)定義的異常/錯誤。這個新
的異常類型是ShortInputException類。它有兩個域——length是給定輸入的長度,atleast則是程序
期望的最小長度。
在except從句中,我們提供了錯誤類和用來表示錯誤/異常對象的變量。這與函數(shù)調(diào)用中的形參
和實(shí)參概念類似。在這個特別的except從句中,我們使用異常對象的length和atleast域來為用戶
打印一個恰當(dāng)?shù)南ⅰ?