AppDividend
Latest Code Tutorials

What is ValueError Exception in Python and How to Handle It

0

Errors detected during the Python program execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in your programs. Errors cannot be handled, while exceptions in Python can be handled at the run time.

Exception handling makes your code more hale and helps anticipate potential failures that would cause your program to stop in an uncontrolled manner.

Errors can be defined as the following types:

  1. Syntax Error
  2. Out of Memory Error
  3. Recursion Error
  4. Exceptions

An exception object is created when a Python script raises an exception. Let’s see the ValueError exception.

What is ValueError Exception in Python

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.

The TypeError exception may be raised by user code to indicate that an attempted operation on an object is not supported and is not meant to be.

Let’s see the ValueError Exception example.

import math

math.sqrt(-10)

Output

Traceback (most recent call last):
  File "/Users/krunal/Desktop/code/pyt/database/app.py", line 3, in <module>
    math.sqrt(-10)
ValueError: math domain error

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

How to Handle ValueError Exception in Python

To handle the ValueError exception, use the try-except block. 

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.

Our program can raise ValueError in int() and math.sqrt() functions. So, we can create a nested try-except block to handle both of them.

Conclusion

Passing arguments of the wrong data type should result in the TypeError, but passing arguments with a wrong value should result in the ValueError.

That is it for the ValueError exception in Python.

See also

Python cv2 module not found error

Leave A Reply

Your email address will not be published.

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