What is ValueError in Python?

Overview

ValueError in Python is raised when a user gives an invalid value to a function but is of a valid argument. It usually occurs in mathematical operations that will require a certain kind of value, even when the value is the correct argument.

Imagine telling Python to take the square root of a negative integer. Now, even though the negative integer is a number argument, the value is just invalid, and Python will return a value error message.

How to identify a valueError

Let’s write a simple code that will return a valueError.

Code

import math
print(math.sqrt(-1)

Output

ValueError: math domain error

As seen from the output of our code above, there is a ValueError arising from an invalid input in the code. This is so because, mathematically, there is nothing like the square root of a negative integer (-0).

How to handle ValueError

We use the 'try' and 'except' block to handle or check for errors arising from an invalid output.

Code

import math
try:
    print(math.sqrt(-1))
except ValueError:
    print('You can not get take the square root of a negative number ')

Output

You can not get take the square root of a negative number

The above program shows that we were able to check for the ValueError in our code using the 'try' and 'except' blocks.

Summary

To check for or handle ValueError in Python, a programmer should include the 'try' and 'except' block.