
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to catch ValueError using Exception in Python?
While passing arguments to a Python function, if the datatype of the given values is different from the function parameters, a TypeError is raised. But if the type of the argument is accurate and its value is inappropriate, a ValueError exception is raised
In this article, you will learn how to catch ValueError exceptions using the general Exception class, which can catch all built-in exceptions, including ValueError.
The ValueError exception commonly occurs when -
- You convert a string to an integer or float, but the string is not valid
- You pass an invalid value to functions like math.sqrt()
- You unpack an iterable with the wrong number of elements
Using try-except to Catch ValueError
You can use a try-except block to catch any exception, including ValueError, by using (specifying) the Exception class in the except block.
Example
In this example, we try to convert a string that cannot be converted to an integer, resulting in a ValueError -
try: num = int("abc") except Exception: print("Caught an exception while converting to integer.")
Following is the output obtained -
Caught an exception while converting to integer.
Using Exception to Catch ValueError
You can also catch the exception object to print the specific message, which exactly explains the cause of the exception (generated by Python).
Example
In this example, we display the actual error message using the exception object -
try: value = float("hello") except Exception as e: print("Caught Exception:", e)
We get the output as shown below -
Caught Exception: could not convert string to float: 'hello'
Handling ValueError During Input
Typically, ValueError occurs while reading numeric values from the user. If we catch it, we can prevent the abrupt termination of the program and execute the statement that follows the exception.
Example
In the following example, we catch ValueError to handle non-numeric input -
try: user_input = input("Enter a number: ") number = int(user_input) print("You entered:", number) except Exception: print("Caught an exception: invalid input.")
The error obtained is as shown below -
Enter a number: fh6 Caught an exception: invalid input.
Using ValueError Instead of Exception
Although we can catch the ValueError exception using the Exception object, it is recommended to catch ValueError when we are sure that it is the exception that may occur.
Example
Following is an example -
try: number = int("abc123") except ValueError: print("Caught ValueError: Cannot convert string to int.")
The result produced is as follows -
Caught ValueError: Cannot convert string to int.