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