class ShortInputException(Exception):
'''A user-defined exception class'''
def __init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast
try:
s=raw_input('Enter something-->')
if len(s)<3:
raise ShortInputException(len(s),3)
except KeyboardInterrupt: #当用户取消输入时,引发此异常
print "Cancel it "
except EOFError:
print '\n Why did you do an EOF on me?'
was expecting at least %d' %(x.length,x.atleast)
else:
print 'No exception was raised'
'''A user-defined exception class'''
def __init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast
try:
s=raw_input('Enter something-->')
if len(s)<3:
raise ShortInputException(len(s),3)
except KeyboardInterrupt: #当用户取消输入时,引发此异常
print "Cancel it "
except EOFError:
print '\n Why did you do an EOF on me?'
except ShortInputException,x:
'''如果引发该异常ShortInputException实例赋给后面那个名字x;当用户输入内容长度<3时,引发此异常;建议此处使用except ShortInputException as x:如果引发该异常ShortInputException实例赋给后面那个名字x
'''
was expecting at least %d' %(x.length,x.atleast)
else:
print 'No exception was raised'
本文探讨了在Python中如何通过定义自定义异常类来处理用户输入长度不足的情况,包括异常捕获和处理机制。
1094

被折叠的 条评论
为什么被折叠?



