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 trialAassem Hadiouche
6,570 PointsQuestion 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
231,269 PointsThe "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").
ChiaChi Chang
273 Pointsunderstood 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
231,269 PointsThe 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.
Zahkyi Ferguson
504 PointsZahkyi Ferguson
504 PointsThank you for your explanation. So "as" essentially creates variables for error objects, what kind of value is "as"?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsIt's an operational keyword, like "except".