Reputation: 428
I'm using index()
on a string to find the occurrence of a substring.
When the substring does not exist within the string, I get:
"ValueError: substring not found".
I want my program to be able to recognize when this is happening, but I don't know how to turn the ValueError
into something useful. For example, how can I use getting a ValueError
in an if
statement?
Upvotes: 2
Views: 3926
Reputation: 6086
Generally you could use try and except for catching exceptions but in this case as mentioned by John you could just use find().
try:
#your code that raises the exception
except ValueError:
#turn it into something useful
Upvotes: 7
Reputation: 249123
Don't wait for the exception. Use find()
instead of index()
and you will avoid having exceptions at all. Just test for not-found and be done with it.
Upvotes: 5