What is ValueError Exception and How to Fix It

The ValueError exception in Python is raised when the method receives the argument of the correct data type but an inappropriate value. The associated value is a string giving details about the data type mismatch.

Example

import math

math.sqrt(-10)

Output

ValueError: math domain error

As you can see that we got the ValueError: math domain error.

How to fix the ValueError Exception in Python

To fix the ValueError exception, use the try-except block. The try block lets you test a block of code for errors. The except block enables you to handle the error.

import math

data = 64

try:
  print(f"Square Root of {data} is {math.sqrt(data)}")
except ValueError as v:
  print(f"You entered {data}, which is not a positive number")

Output

Square Root of 64 is 8.0

Now, let’s assign the negative value to the data variable and see the output.

import math

data = -64

try:
  print(f"Square Root of {data} is {math.sqrt(data)}")
except ValueError as v:
  print(f"You entered {data}, which is not a positive number")

Output

You entered -64, which is not a positive number

You can see that our program has raised the ValueError and executed the except block.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.