Search code examples
python-3.xexceptionbuffer-overflow

How to clear the current call stack on exception before re calling the function again in python3?


I am extremely new to python and error handling. Currently, I have written a program which access a user's email account and gets the contents of the requested email. I use a number based menu to set the filters to select the required email. As is common with any numeric input in python, this gives rise to a potential ValueError which needs to be handled. For that, I use an except statement. Inside the except statement, I inform the user of the fact that the field requires a numeric input and then call the function to take the input again, hence resulting in a tail recursion. But, I realized that this is not an ideal solution since eventually, if enough errors are generated, it would lead to a buffer over flow.

So, my question is, is there a better way to achieve the same. As in, is there a way to clear the current call stack and THEN restart the program right from the beginning so as to prevent a buffer over flow?

Thanks for any suggestions.

I have tried to look up several articles on stack over flow and otherwise, but none of them seem to cover the problem I am facing.


Solution

  • This is a fairly basic example but I think I shows what I was talking about well enough

    def getEmail():
        # email logic
        inp = int(input('Input a number >>> '))  # conversion that can throw an error
        return inp
    
    
    while 1:  # loops forever
        try:
            print(getEmail())
        except ValueError:
            print('Numeric input required')
    

    This is quite a good solution since the exception pushes up the stack automatically, meaning that you don't have to call the function inside itself, instead you can let it complete and then call it again.