Cara menggunakan except valueerror python

Cara menggunakan except valueerror python

Table of Contents

  • How to resolve ValueError Exception in Python
  • Different Uses of the ValueError Exception
  • Example-1: Raise the ValueError for Incorrect Data
  • Example-2: Handle the ValueError by Using Try-Except Block
  • Example-3: Raise the ValueError in a Function
  • Example-4: Use of the ValueError Inside and Outside of the Function
  • Example-5: Use of the ValueError with Other Error
  • Example-6: Use of the ValueError with the Command-Line Argument
  • What are the 3 types of errors in Python?
  • What is the difference between ValueError and type error?
  • What kind of error is a types error in Python?
  • What is TypeError and ValueError in Python?

Table of Contents

  • How to resolve ValueError Exception in Python
  • Different Uses of the ValueError Exception
  • Example-1: Raise the ValueError for Incorrect Data
  • Example-2: Handle the ValueError by Using Try-Except Block
  • Example-3: Raise the ValueError in a Function
  • Example-4: Use of the ValueError Inside and Outside of the Function
  • Example-5: Use of the ValueError with Other Error
  • Example-6: Use of the ValueError with the Command-Line Argument
  • About the author
  • What are the 3 types of errors in Python?
  • What is the difference between ValueError and type error?
  • What kind of error is a types error in Python?
  • What is TypeError and ValueError in Python?

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.

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 in Python 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 resolve ValueError Exception in Python

To resolve the ValueError exception, use the try-except block. The try block lets you test a block of code for errors. The except block lets you handle the error.

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

ValueError: Math Domain Error in Python

No Such File Or Directory Error in Python

Python cv2 module not found error

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.

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.

What are the 3 types of errors in Python?

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

What is the difference between ValueError and type error?

A TypeError occurs when an operation or function is applied to an object of inappropriate type. A ValueError occurs when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

What kind of error is a types error in Python?

TypeError. The TypeError is thrown when an operation or function is applied to an object of an inappropriate type.

What is TypeError and ValueError in Python?

Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError , but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError .