Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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?