您的位置:首页 > 编程语言 > Python开发

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

2012-04-11 18:35 639 查看
下午一直受困与简明教程try_except.py中的except ShortInputException , x:的3.2版本的实现方法,

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

有点恍然大悟的感觉~

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

#!/usr/bin/python
# Filename : try_except.py

import sys

try:
s = 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

print('Done ~ . ~')

class ShortInputException(Exception):
''' A user-defined exception class. '''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast

try:
s = input('Enter somethin -->')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue sa usual here
except EOFError:
print('\nWhy did you do an EOF on me?')
except ShortInputException as x:

print('ShortInputException: The input was of length %d,\
was expecting at least %d' %(x.length, x.atleast))
else:
print('No exception was raised!')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: