You can handle a ValueError in Python using a try and except block. This allows you to catch the exception and execute alternative code when the error occurs. Here’s an example:
Example of Handling ValueError
try:
num = int("abc") # This will raise a ValueError
except ValueError:
print("Invalid input! Please enter a valid integer.")
Explanation
- try block: Contains the code that may raise a
ValueError. - except block: Catches the
ValueErrorand executes the code within it, allowing you to handle the error gracefully.
You can also handle multiple exceptions in the same try block if needed:
try:
num = int("abc") # This will raise a ValueError
result = 10 / num # This may raise a ZeroDivisionError if num is 0
except ValueError:
print("Invalid input! Please enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero!")
In this example, both ValueError and ZeroDivisionError are handled appropriately.
