How to handle ValueError in Python

ValueError is a built-in exception class in Python that is raised when an operation or function receives an argument that has the right type but an inappropriate value. For example, trying to convert a string that is not a valid number to an integer will raise a ValueError.

Example of ValueError

>>> int('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hello'

How to catch ValueError

To handle ValueError, we can use a try-except block and catch the exception using the except keyword. We can also access the error message using the .args attribute of the exception object. For example:

try:
    num = int(input('Enter a number: '))
    print(f'You entered {num}')
except ValueError as e:
    print(f'Invalid input: {e.args[0]}')

How to raise ValueError

Sometimes, we may want to raise a ValueError ourselves if we detect that the input or argument is not valid for our function or operation. To do this, we can use the raise keyword and pass a custom error message as an argument to the ValueError class. For example:

def factorial(n):
    if n < 0:
        raise ValueError('n must be non-negative')
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

Example of raising ValueError

>>> factorial(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in factorial
ValueError: n must be non-negative

Most Common Value Errors In Python

Conclusion

ValueError is a common exception that occurs when the value of an argument or input is not suitable for the function or operation. We can handle it using try-except blocks and raise it using the raise keyword. We can also access the error message using the .args attribute of the exception object.

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 90

Leave a Reply

Your email address will not be published. Required fields are marked *