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 trialChristopher Caron
1,270 PointsI can't understand ValueError as err
Okay so I think I am confused -- sorry if this was answered elsewhere but I couldn't find it.
except ValueError as err:
print("Oh no! That's not a valid value. Try again.")
print("({})".format(err))
In that code, as soon as we get a ValueError it is going to be printing "Oh no! That's not a valid value. Try again." Right?
And then on the next line, it knows to print what we wrote in the function. How does it know to print what we wrote in the function? Is it because we assigned ValueError to err (sorry if "assigned" isn't the right term there) so when we use .format(err) it knows to reference ValueError in our function? If that's the case, why can't we just say
except ValueError
print("Oh no! That's not a valid value. Try again.")
print("({})".format(ValueError))
If that's NOT the case, what am I missing?
1 Answer
Alexander Davison
65,469 PointsValueError
is not a value itself, it is actually a class. So except ValueError as err
catches errors that are instances of the ValueError
class and err
holds the error string itself
Using as
in this case isn't "assignment". In other cases it isn't assignment either, but is holding an alias of a value as an identifier.