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 trialBotshelo Tsogo Tiroyamodimo
3,057 PointsDont understand the ValueError as err and why we use it on the .format function
Why do we add as err and then include it on our print statement on the .format(err), i still don't understand it and how come when u place the .format(err) on the print command it prints the statement, is it just to abbreviate the ValueError to something shorter?
1 Answer
Chris Freeman
Treehouse Moderator 68,457 PointsGood question. When coding an except
statement, ValueError
is the type of error expected meaning is it a class definition of the error. To access the current error instance, using "as err
" says "allow me to refer to the current error instance as 'err'". Using print(err)
would call the __str__
method of the instance.
>>> try:
... int("string")
... except ValueError as err:
... print("===ERR===\n", err)
... print("===ARGS===\n", err.args)
... print("===TRACEBACK===")
... print(err.with_traceback())
...
===ERR===
invalid literal for int() with base 10: 'string'
===ARGS===
("invalid literal for int() with base 10: 'string'",)
===TRACEBACK===
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'string'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
TypeError: with_traceback() takes exactly one argument (0 given)
FYI, the method with_traceback()
also raises an error, which is why I used two print statements:
>>> try:
... try:
... int("string")
... except ValueError as err:
... print("===TRACEBACK===\n", err.with_traceback())
... except:
... print("error raised")
...
error raised