Search code examples
pythondatabasepython-3.xcustom-exceptions

How to gain program control back after handling the exception?


 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.


Solution

  • 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