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

Aassem Hadiouche
Aassem Hadiouche
6,498 Points

Question about logic of "as err"

When Craig is explaining how to get the ValueError message from the function, he says to change the "except ValueError:" code to "except ValueError as err:" and then he also needs to print a message with ".format(err)" to get the original message from the function.

It's not clicking for me how python knows to refer to the "raise ValueError" in the function when you are in the try block of code.

Do you have to use the keyword "err" in this case?

What does "as" do so that the compiler knows to refer back the "raise ValueError" in the function?

I imagine there's some detail I'm forgetting that puts all the pieces together but it's not coming to me. Thanks in advance for any and all help!

2 Answers

Steven Parker
Steven Parker
215,954 Points

The "except" by itself responds to the ValueError.

What the "as" does is save the error object where you can get to it in the handler code. The term after "as" is the name of the variable where you want it to be saved (in this case, "err").

Zahkyi Ferguson
Zahkyi Ferguson
504 Points

Thank you for your explanation. So "as" essentially creates variables for error objects, what kind of value is "as"?

Steven Parker
Steven Parker
215,954 Points

It's an operational keyword, like "except".

ChiaChi Chang
ChiaChi Chang
273 Points

understood about the "as" is creating a variables

but how compiler knows the variable after "as" ("err" in this case) refer back the "raise ValueError" in the function? I thought it could be showed the result of "except" again

Steven Parker
Steven Parker
215,954 Points

The systems puts an object containing data about the exception into the variable when the exception happens. In this case, it is caused by the "raise" statement.