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 trial

Python Python Basics Functions and Looping Raising Exceptions

Aidan L.
Aidan L.
1,158 Points

What does err do in Python

I dont understand what `ValueError as err' does

2 Answers

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

ValueError as err says, create a variable called err and pass the error class in that variable. We are dynamically creating a variable on the fly and it can be named anything like any other variable. It's common convention to call it err or even just e. This gives us the ability to catch various errors and handle them gracefully.

Here's it is in code:

try:
    a = 'abc'
    int(a)
except ValueError as any_old_name:
    print("any_old_name has the type of {}".format(type(any_old_name)))
    print("\nI'm using any_old_name for the error details--> {}".format(any_old_name))

#outputs
any_old_name has the type of <class 'ValueError'>

I'm using any_old_name for the error details--> invalid literal for int() with base 10: 'abc'
Aidan L.
Aidan L.
1,158 Points

I see, but I’m the video, by assigning ValueError into a variable, it “fix” the code and the previous if statement would raise an error. But without the variable ‘err’. The code wouldn’t raise an error.

Spencer Hurrle
Spencer Hurrle
3,128 Points

I think you're confused about the same thing I was initially. I couldn't figure out how "err" was being tied to our "if" statement. After playing around with different errors, it appears as though adding "as err" and putting "err" in a print statement is simply giving an extra line of output which details the error. If you respond "no" when the program asks how many are splitting the check, a line will come up saying "(invalid literal for int() with base 10: 'no')".

Having the if <= 1 statement seems to be telling the program exactly what to print in case we catch that specific response