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 trialAndrew Uzoka
1,949 Pointscould someone help explain the raise, try exception a bit more i am finding it a bit confusing
could someone help explain the raise, try exception a bit more i am finding it a bit confusing
6 Answers
jhon white
20,006 Pointswhile True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again...")
So, as you see throght your program maybe there is something could goes wrong, like invild input from the user or some calculations or type casting go south , so you need to anticipate that by putting your code in try/except block. First, you need to put your best case case in try block. Second, put your error case in exception block. You can read more in python doc for more information. Good luck!!
jhon white
20,006 PointsRaise keyword to raise your own exception such as in your code you don't wanna user input to be less zero and you wanna to make it an exception so, you use the raise keyword to do that. On the other hand try/except for python or logic exception like value exceptions or divide by zero. and Yes, rise keyword will terminate your code execution.
jhon white
20,006 PointsNo, you don't need raise in try/except cuz most of the exception build in python , but you can in include the excepation you raise useing raise keyword in your try/except block .
Andrew Uzoka
1,949 Pointsokay.. so what is the raise keyword needed and what do it actually do in order to allow the try keyword to be called on
jhon white
20,006 Pointsx = -1
if x < 0: raise Exception("Sorry, no numbers below zero")
The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.
Andrew Uzoka
1,949 Pointsso once the raise exception has been meet it then moves to the try or does it terminate before it tries
Andrew Uzoka
1,949 Pointsokay but for the try/except do you need to use the raise keyword for the exception to run?