简体   繁体   中英

Printing Multiple exceptions

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

I have written this code to deal with exception. If test_variable < 0 , I want the user to notify about both the problems ie

  1. TestFailure: Test Variable should not be negative

  2. TestAbort: Test Variable should not be negative.

When I'm entering the proper valid value via keyboard ie when test_variable > 0 , it prints it twice correctly as I'm passing it to both the functions but when I enter negative value for test variable, it's giving me just "TestFailure: Test Variable should not be negative". I understood that when TestFailure is raised, it's exception (message body) came in e and we are getting it by printing e but what's wrong happening in case of TestAbort? Is it a syntax mistake?

Might not be the most efficient, but you can split it into separate try methods:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM