Skip to content

Python ValueError exception

  • by

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

Python ValueError exception examples

A simple example code gets ValueError with mathematical operations, such as the square root of a negative number.

import math

math.sqrt(-100)

Output:

Python ValueError exception

Handling ValueError Exception
Use the try-except block to handle the ValueError exception. The lines of code that can throw the ValueError should be placed in the try block, and the except block can catch and handle the error.

import math

x = -100
try:
math.sqrt(x)
except ValueError:
print(f'You entered {x}, which is not a positive number.')

Output: You entered -100, which is not a positive number.

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading