Show
Table of Contents
Table of Contents
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:
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) OutputTraceback (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 PythonTo 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") OutputSquare 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") OutputYou 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. ConclusionPassing 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 alsoValueError: 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 ExceptionThe uses of ValueError have been shown in the next part of this tutorial. Example-1: Raise the ValueError for Incorrect DataCreate 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 BlockCreate 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: except ValueError: 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 FunctionThe 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 #Call the function with two numbers 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 FunctionCreate 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 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 ErrorCreate 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: 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 ArgumentCreate 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 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. ConclusionThe 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 . |