python 处理异常问题,求解决

love-py 2011-11-14 01:49:34
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 something -->')
if len(s) < 3:
raise ShortInputException(len(s), 3)

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.')


问题:
Enter something -->
Traceback (most recent call last):
File "C:\Documents and Settings\Administrator\桌面\PYTHON\raising.py", line 15, in <module>
except ShortInputException(x):
NameError: name 'x' is not defined
...全文
80 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
libralibra 2011-11-14
  • 打赏
  • 举报
回复
说句实话,python的exception机制不喜欢

import traceback

try:
1/0
except Exception, e:
exstr = traceback.format_exc()
print exstr

panghuhu250 2011-11-14
  • 打赏
  • 举报
回复

except ShortInputException as x:
print str(x)

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧