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

could 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

while 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!!

Raise 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.

No, 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 .

okay.. so what is the raise keyword needed and what do it actually do in order to allow the try keyword to be called on

x = -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.

so once the raise exception has been meet it then moves to the try or does it terminate before it tries

okay but for the try/except do you need to use the raise keyword for the exception to run?