Python

Handling the ValueError Exception in Python

When an error occurs at the time of executing any script, then it is called an exception. The try-except block is used to handle exceptions in Python. Many built-in exceptions exist in Python to handle common errors, such as IndexError, KeyError, NameError, TypeError, ValueError, etc. The ValueError occurs in Python when a correct argument type is passed but an incorrect value is passed to a function. This type of error mainly appears for mathematical operations. When the ValueError occurs and the way of handling this error in Python has been shown in this tutorial.

Different Uses of the ValueError Exception

The uses of ValueError have been shown in the next part of this tutorial.

Example-1: Raise the ValueError for Incorrect Data

Create a Python file with the following script that will raise a ValueError where the int() function has been used to convert a string value.

# Define the first variable
number1 = 100

# Define the second variable
number2 = int('Hello')

# Print the sum of two variables
print(number1 + number2)

Output:

The following output will appear after executing the above script. The output shows that the ValueError has occurred at line number 4 where the int() function has been used to covert the string, ‘Hello’.

Example-2: Handle the ValueError by Using Try-Except Block

Create a Python file with the following script that will take the age value from the user. If a non-numeric value will be taken from the user for the age value, then the try block will throw the ValueError exception and print the custom error message. If the valid age value will be taken from the user, then the message will be printed based on the age value.

try:
    #Take the number value from the user
    age = int(input("Enter your age: "))
    '''
    Check the number is greater than or equal to 25
    and less than or equal to 55
    '''

    if age >= 35 and age <= 55:
       print("You are eligible for this task.")
    else:
       print("You are not eligible for the task.")

except ValueError:
    #Print message for ValueError
    print("Only alphabetic characters are acceptable.")

Output:

The following output will appear after executing the above script for the input values, 56, 45, 23, and ‘twenty’. Here, the ValueError has occurred for the input value, ‘twenty’ which is invalid.

Example-3: Raise the ValueError in a Function

The ValueError can be generated without a try-except block by using the raise keyword inside the Python function. Create a Python file with the following script that will calculate the multiplication of two integer numbers. If any invalid argument value will be passed into the function, then the ValueError will be raised.

# Define the function for multiplication
def Multiplication(a, b):
    # Check the type of the arguments
    if type(a) == str or type(b) == str:
        # Raise the ValueError
        raise ValueError('The value of any or both variables is /are not a number.')
    else:
        # Multiply the variables
        result = a*b
        # Print the multiplication result
        print("Multiplication of % d and %d is %d" % (a, b, result))


# Call the function with two numbers
Multiplication(4, 3)
# Call the function with one number and a string
Multiplication(5, '6')

Output:

The following output will appear after executing the above script. Here, when the function has been called with the values 5 and ‘6’, then the ValueError has been raised for the invalid value, ‘6’.

Example-4: Use of the ValueError Inside and Outside of the Function

Create a Python file with the following script that shows the uses of ValueError inside and outside the function. Here, the check() function has been defined to find out whether a number is positive or negative. The function will raise the ValueError when an invalid argument value will be passed to the function. The try-except block will catch the ValueError passed from the function and print the error message.

# Define the function
def Check(n):
    try:
        # Convert the value into the integer
        val = int(n)
        # Check the number is positive or negative
        if val > 0:
            print("The number is positive")
        else:
            print("The number is negative")
    except ValueError as e:
        # Print the error message from the function
        print("Error inside the function: ", e)
        raise


try:
    # Take input from the user
    num = input("Enter a number a value: ")
    # Call the function
    Check(num)
except ValueError as e:
    # Print the error message
    print("Error outside the function: ", e)

Output:

The following output will appear after executing the above script with the input values of 6, -3, and ‘d’. Here, the ValueError has occurred inside and outside of the function for the input value, ‘d’.

Example-5: Use of the ValueError with Other Error

Create a Python file with the following script that will open a file for reading and print the content of the file. If the filename that has been used in the script is not accessible, the IOError will be generated, and if the file contains any alphabetic character, then the ValueError will be generated.

try:
    #Open the file for reading
    fh = open('sales.txt')
    #Define while loop to read file line by line
    while fh:
        #Convert the line into the integer
        value = int(fh.readline())
        #Print the value
        print(value)
except (ValueError, IOError):
    '''
    Print the error message if the file is
    unable to read or the file contains
    any string data
    '''

    print("ValueError or IOError has occurred.")

Output:

The following output will appear after executing the above script. Here, the ValueError has been generated because the sales.txt file contains alphabetic characters at line number 6.

Example-6: Use of the ValueError with the Command-Line Argument

Create a Python file with the following script that will take a number from the command-line argument value. The particular message will be printed if a numeric value is provided in the command-line argument, otherwise, the ValueError will be generated and an error message will be printed.

#Import sys module
import sys
try:
    #Check the number of arguments
    if len(sys.argv) > 1:
       #Convert the argument value into the integer
       num = int(sys.argv[1])
       #Check the number is greater than or equal to 100
       if num >= 100:
          print("You have to enter a number less than  100.")
       else:
          print("The entered number is %d" % num)
    else:
       print("No argument value is given.")
except ValueError:
    #Print message for ValueError
    print("You have to type a number")
finally:
    #Print the termination message
    print("The program is terminated.")

Output:

The following output will appear after executing the above script when the script is executed without any argument, with the argument values 600 and 60.

Conclusion

The purpose of using the ValueError exception has been shown in this tutorial by using multiple examples for helping the Python users to know the uses of this exception properly.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.