求助贴:python学习中引发异常程序遇到问题
我是初学Python,属于菜鸟水平
我在运行以下程序时,如果输入ab,总提示我红色语句中x未被定义,去掉括号换成逗号后总说用类名定义x之间的逗号有问题,这是什么原因啊?我用的是Python3.2.3
class ShortInputException(Exception):
'''A usere-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')
[解决办法]
except ShortInputException as x:
[解决办法]
except ShortInputException as x:
[解决办法]
在python3中,语法稍稍和python2.7不一样:
>>> try:... print(1 / 0)... except Exception as exc:... raise RuntimeError("Something bad happened") from exc...Traceback (most recent call last): File "<stdin>", line 2, in <module>ZeroDivisionError: int division or modulo by zeroThe above exception was the direct cause of the following exception:Traceback (most recent call last): File "<stdin>", line 4, in <module>RuntimeError: Something bad happened
[解决办法]
>>> try:... print(1 / 0)... except Exception as exc:... raise RuntimeError("Something bad happened") from exc...