Ask coding questions

← Back to all posts
Why is "except ValueError:"/"except ValueError as ve:" invalid syntax
Carnage498 (64)

I have searched and I keep ending up with nothing. On some sites it says "except ValueError as ve:" is correct but on others it says "except ValueError:" is correct. neither work here. I have no idea what to do so I guessed this was the last option. Hopefully I get an answer.

Answered by Coder100 (18934) [earned 5 cycles]
View Answer
Coder100 (18934)

You got the syntax wrong, it looks like this:

except: ValueError:

as you can see, the except is actually inline with try.
So unindent.

InvisibleOne (3227)

Try and except works like this:

  do this
  if error do this

You can get the exact error that was thrown like this:

except Exception as e:

What this does is trigger when any exception occurs, and then store that exception in a variable e, sort like opening a file:

with open() as file:

The ValueError one is just one that only happens when a ValueError accurs, I don't know all the different types of errors but I'm sure you can just google it.