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.
Dont 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?
Chris FreemanTreehouse Moderator 67,912 Points
Good question. When coding an
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