0

 am developing a python application . I have validated customer id from database. Means if the entered custid is present in database, i am raising an exception. In exception class i am printing the message . So far it is printing the message. But i am not sure how to get control back to the statement where i am taking the input.  main app

Custid=input("enter custid)
Validate_custid(Custid) 
Print(Custid)

validate_custid module

From connections import cursor
From customExceptions import invalidcustidException
Def validate_custid(custid):
    Cursor.execute("select count(custid) from customer where custid=:custid",{"custid":custid}) 
    For row in cursor: 
        Count=row[0] 
        If Count==0: 
            Raise invalidcustidException

So far its printing the message in exception.now i want my program to take custid as input whenever this exception occurs. The process should iterate until user enters valid custid.

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131

3 Answers3

1

You'll want a try except block.

try:
  # portion of code that may throw exception
except invalidcuspidError:
  # stuff you want to do when exception thrown

See https://docs.python.org/2/tutorial/errors.html for more.

personjerry
  • 1,045
  • 8
  • 28
  • Yup. I know that.but in exceltions except clause, i want to call the function again which was throwing exception until it accepts valid input.i.e. if user enters invalid custid,it should throw exception. Print the message, and will call itself until it gets valid input from customer. – Bhushan Gadekar Nov 04 '15 at 01:22
  • @BhushanGadekar Perhaps this: Wrap the try block in a while loop that checks a flag. At the beginning of the loop set the flag to false. If the exception triggers, set the flag to true. – personjerry Nov 04 '15 at 01:25
1

What you are trying to do is called exception handling. I think the Python docs explain this better than me, so here you go: https://docs.python.org/2/tutorial/errors.html#handling-exceptions

Martin Hallén
  • 1,492
  • 1
  • 12
  • 27
1

You should use a try-except block with else statement:

while True:
    custid = input('Input custom Id: ')
    try:
        # Put your code that may be throw an exception here
        validate_custid(custid)
    except InvalidcustidException as err:
        # Handle the exception here
        print(err.strerror)
        continue # start a new loop
    else:
        # The part of code that will execute when no exceptions thrown
        print('Your custom id {} is valid.'.format(custid))
        break # escape the while loop

Take a look at here: https://docs.python.org/3.4/tutorial/errors.html#handling-exceptions

Vuong Hoang
  • 149
  • 8