[简明Python教程3.2版本实现] try_except.py

  下午一直受困与简明教程try_except.py中的except ShortInputException , x:的3.2版本的实现方法,

最后得出用except ShortInputException as x:可以实现。

有点恍然大悟的感觉~

额......菜鸟Python初学者伤不起,有木有,有木有!

 

 1 #!/usr/bin/python
 2 # Filename : try_except.py
 3 
 4 import sys
 5 
 6 try:
 7     s = input('Enter something -->')
 8 except EOFError:
 9     print('\nWhy did you do an EOF on me?')
10     sys.exit() # exit the program
11 except:
12     print('\nSome error/exception occurred!')
13     # here, we are not exiting the program
14 
15 print('Done ~ . ~')
16 
17 class ShortInputException(Exception):
18     ''' A user-defined exception class. '''
19     def __init__(self, length, atleast):
20         Exception.__init__(self)
21         self.length = length
22         self.atleast = atleast
23 
24 try:
25     s = input('Enter somethin -->')
26     if len(s) < 3:
27         raise ShortInputException(len(s), 3)
28     # Other work can continue sa usual here
29 except EOFError:
30     print('\nWhy did you do an EOF on me?')
31 except ShortInputException as x:
32     
33     print('ShortInputException: The input was of length %d,\
34 was expecting at least %d' %(x.length, x.atleast))
35 else:
36     print('No exception was raised!')

 

posted @ 2012-04-11 18:35  听歌的麦子  阅读(280)  评论(0)    收藏  举报