如何处理ValueError?

2 投票
2 回答
3835 浏览
提问于 2025-04-17 18:13

我在一个字符串上使用 index() 方法来查找一个子字符串的出现位置。

当这个子字符串在字符串中不存在时,我会得到:

"ValueError: substring not found".

我希望我的程序能够识别这种情况,但我不知道怎么把 ValueError 转换成有用的信息。例如,我该如何在 if 语句中使用这个 ValueError 呢?

2 个回答

5

别等着出错再处理。用 find() 代替 index(),这样你就可以完全避免出错。只需要检查一下有没有找到就可以了,简单明了。

7

通常情况下,你可以使用try和except来捕捉错误,但在这个例子中,正如约翰提到的,你可以直接使用find()方法。

try:
   #your code that raises the exception
except ValueError:
   #turn it into something useful

撰写回答