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

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
229,695 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?