class ShortInputException(Exception):
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.')
运行报错,显示:
Traceback (most recent call last):
File "D:\Study\Python\Project\except\except.py", line 31, in <module>
except (ShortInputException, x):
NameError: name 'x' is not defined
还请各位大侠帮忙解决!
6 个解决方案
#1
except ShortInputException, x:
不需要括号
#2
赞同
#3
我用的是3.3的版本,现在加括号不加括号都有问题,加了之后与楼主问题一样的,
不加括号的话,显示有“语法错误”,光标会停在这一行的逗号处,继续关注。
不加括号的话,显示有“语法错误”,光标会停在这一行的逗号处,继续关注。
#4
python 3中应为:
try: 1/0
except Exception as x:
print(x)
#5
py3要语法要加上 as
#6
py26也可以as吧。
#1
except ShortInputException, x:
不需要括号
#2
赞同
#3
我用的是3.3的版本,现在加括号不加括号都有问题,加了之后与楼主问题一样的,
不加括号的话,显示有“语法错误”,光标会停在这一行的逗号处,继续关注。
不加括号的话,显示有“语法错误”,光标会停在这一行的逗号处,继续关注。
#4
python 3中应为:
try: 1/0
except Exception as x:
print(x)
#5
py3要语法要加上 as
#6
py26也可以as吧。