Python Python Basics All Together Now Handle Exceptions

Botshelo Tsogo Tiroyamodimo
Botshelo Tsogo Tiroyamodimo
648 Points

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?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,951 Points

Good 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