[python] raise statement
1. raise an exception defined by user.
1 class MyException(Exception): 2 ''' An exception defined by user,inherit from Top Exception''' 3 def __init__(self,length,atleastlength): 4 Exception.__init__(self)#invoking parent __init__() method manually 5 self.length = length 6 self.atleastlength = atleastlength 7 8 try: 9 str1 = raw_input('input something here:') 10 if len(str1) < 3: 11 raise MyException(len(str1),3) 12 # raise an Exception defined by user, if not satisfied with certain condition. 13 except MyException, err: 14 # capture an exception defined by user 15 print 'Input short error: the input is the lengthof %d,\ 16 and was excepting at least %d'%(err.length,err.atleastlength) 17 else: 18 print 'No exception is raised' 19 20 ##input something here:gg 21 ##Input short error: the input is the lengthof 2, and was excepting at least 3 22 ##>>> ================================ RESTART ================================ 23 ##>>> 24 ##input something here:gggg 25 ##No exception is raised 26 ##>>>
2 Excepition hierarchy