class TestFailure( ArithmeticError ):
pass
def failuremsg( test_variable ):
if test_variable < 0:
raise TestFailure, "TestFailure: Test Variable should not be negative"
return( test_variable )
class TestAbort(SystemExit):
pass
def abortmsg(test_variable):
if test_variable < 0:
raise TestAbort, "TestAbort : Test Variable should not be negative "
return( test_variable )
while 1:
try:
test_variable = float( raw_input( "\nPlease enter a test_variable: " ) )
print "test_variable :", failuremsg( test_variable )
print "test_variable :", abortmsg( test_variable )
except ValueError:
print "The entered value is not a number"
except (TestFailure, TestAbort) as e :
print e
#except TestAbort, exception:
#print exception
else:
break
我已编写此代码来处理异常。如果test_variable < 0
,我希望用户通知这两个问题,即
TestFailure:测试变量不应为负数
TestAbort:测试变量不应为负数。
当我通过键盘输入正确的有效值时,即test_variable > 0
时,它会正确打印两次,因为我将它传递给两个函数,但是当我为测试变量输入负值时,它只给我&#34; TestFailure:测试变量不应该是负面的&#34;。我明白当TestFailure被提出时,它的例外(消息体)出现了,我们通过打印e来获取它,但是在TestAbort的情况下发生了什么错误?这是语法错误吗?
答案 0 :(得分:0)
可能不是最有效的,但您可以将其拆分为单独的try方法:
try:
test_variable = float( raw_input( "\nPlease enter a test_variable: " ) )
try:
print "test_variable :", failuremsg( test_variable )
except TestFailure as e:
print e
try:
print "test_variable :", abortmsg( test_variable )
except TestAbort as e:
print e
except ValueError:
print "The entered value is not a number"