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 trialMikael D.D
Courses Plus Student 2,080 PointsHandling 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
231,275 PointsOne 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
Courses Plus Student 2,080 PointsThanks 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
231,275 PointsLooks good. You've implemented exactly what I was suggesting.