读书人

python 处理错误有关问题求解决

发布时间: 2012-03-26 15:46:56 作者: rapoo

python 处理异常问题,求解决
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

[解决办法]

Python code
except ShortInputException as x:  print str(x)
[解决办法]
说句实话,python的exception机制不喜欢
Python code
import   tracebacktry:                1/0except   Exception,   e:                exstr   =   traceback.format_exc()                print   exstr 

读书人网 >perl python

热点推荐