Python Exception : ValueError
A ValueError
in Python occurs when a function receives an argument of the right type but an inappropriate value.
Lets see with an example:
🧪 Converting a string input to an integer
num = int("Hello World !")
🔍 What happens?
This will raise a ValueError
because "Hello World !"
is a string that cannot be converted to an integer.
🧠 Another Example: Using math.sqrt
with a negative number
import math result = math.sqrt(-1)
🔍 Why?
The math.sqrt()
function expects a non-negative number. Passing -1
will raise a ValueError
since square root of a negative number isn't defined in the real number system.
✅ How to handle it
We can catch and handle ValueError
using a try-except
block:
try: num = int("hello") except ValueError as e: print("Caught a ValueError:", e)
0 Comments
Post a Comment