首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

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

2012-03-26 
python 处理异常问题,求解决class ShortInputException(Exception):A user-defined exception class.

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 

热点排行