0
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 i.e

  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 i.e 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?

fredtantini
  • 15,966
  • 8
  • 49
  • 55
NikAsawadekar
  • 57
  • 1
  • 5
  • 2
    When a line causes an exception, the program jumps forward to the matching `except` block, skipping any code in between. If `failuremsg` raises `TestFailure`, then `abortmsg` will never be called. – Kevin Aug 13 '14 at 15:26
  • In a try...except, and in python in general, the first exception raised stops execution dead. – Tritium21 Aug 13 '14 at 15:27
  • @Kevin Okk.. I should have realized this. Thanks. But there's no way that failure of a particular condition willraise 2 exceptions? What I'm trying here is I want to raise bothe TestFailure and TestAbort when test_variable < 0. – NikAsawadekar Aug 13 '14 at 15:40

1 Answers1

0

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"
user1102901
  • 565
  • 1
  • 4
  • 12