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

What is 'raise' exactly, and what does it do?

I don't think I completely understand what raise is for and how it's used. If except can handle common errors very well, doesn't that make the use of raise redundant inside of a try-except block?

For example:

try:
   print( 5/0 )
except ZeroDivisionError:
   raise ValueError("An error occurred!")

What's the difference if we handle it this way:

try:
   print( 5/0 )
except (ZeroDivisionError, ValueError):
   print("An error occurred!")

I searched the web for a good explanation of what raise does and I couldn't find one that is not confusing. Could anyone please break this for me in simple English? Thank you.

1 Answer

Steven Parker
Steven Parker
216,165 Points

:point_right: Print just causes a message to appear, raise creates an error condition.

The message associated with raise is secondary to the primary purpose of creating the error condition. Unless the program handles that condition (with another except), the program will stop running.

Thanks for your answer Steven. It makes sense that it should be different from print. But I'm still not sure what it does here. Are you saying it handles an error even if it didn't occur? If so, why and how is that useful?