Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Functions and Looping Raising Exceptions

Mikael D.D
PLUS
Mikael D.D
Courses Plus Student 2,080 Points

Handling exceptions without exiting program

4 my Pythonic ninjas... after handling the error msg I would like the program to goback asking the same question that first triggered the exception instead of exiting after dispalying error msg. Im assuming I have to insert some code right after the print statement handling the error msg however you know what they say about assuming....

Questions: Is there a function that can perform : 1- go back to the same question that caused the exception without exiting the program 2- alternatively reboot the program from the start.

Thanks for your time!!

2 Answers

Steven Parker
Steven Parker
231,248 Points

One easy technique is to wrap all the code from the question through the error handling in a "while True" loop. Then inside you can "break" to end the loop when you get an error-free result.

If the program is implemented as a function, another trick to cause a complete restart would be to call the main function (and then return) after handling an error.

Mikael D.D
PLUS
Mikael D.D
Courses Plus Student 2,080 Points

Thanks Steven !! I tried this to practice what you explained..I was really exited to see that it works ;) at first I had some issues with indentation and where to put the break but I finally managed please feel free to point out if I did something wrong.

while True:

    try:
        age = int(input("How old are you ? "))
        if age <=0:
            raise ValueError
        print("Ok you are ", age)
        break    
    except ValueError:
        print ("I Need a round number higher than 0 please try again ")

        #thanks to Steven P.
Steven Parker
Steven Parker
231,248 Points

Looks good. :+1: You've implemented exactly what I was suggesting.