In Python, when an error occurs during the execution of code, it is referred to as an exception. Python includes a number of built-in exceptions such as SyntaxError, NameError, ValueError, etc. and the try-except block can be used to handle exceptions.
What is ValueError?
ValueError occurs when a correct argument type but an incorrect value is passed to a function. It typically occurs in mathematical operations that require a specific type of value.
import math print(math.sqrt(100)) print(math.sqrt(-100))
10.0 ValueError: math domain error
As shown in the program output,
ValueError exception is raised as in mathematics we cannot take the square root of a negative number.
Using Try-Except block to handle ValueError
The ValueError exception can be handled by putting your code between the try and except block. If an exception occurs during the execution of code, it will be thrown by try block and the except block will get executed.
import math try: print(math.sqrt(-100)) except ValueError as ve: print('ValueError ::',ve)
ValueError :: math domain error
Raising ValueError in a function
import math def get_sqr_root(num): if num < 0: raise ValueError('Numbers must be positive') return math.sqrt(num) print(get_sqr_root(100)) print(get_sqr_root(-100))
10.0 ValueError: Numbers must be positive
In the above example, the correct argument type but an incorrect value is passed so ValueError is raised.