如何处理ValueError?
问题描述:
我在字符串上使用index()
来查找子字符串的出现。如何处理ValueError?
当子并不在字符串中存在,我得到:
"ValueError: substring not found".
我想我的程序能够在发生这种情况承认,但我不知道如何打开ValueError
成有用的东西。例如,如何在if
声明中使用ValueError
?
答
不要等待异常。使用find()
而不是index()
,你将避免有例外。只需测试未找到并完成它。
答
通常你可以使用try和除了捕获异常,但在这种情况下,如约翰所说,你可以使用find()。
try:
#your code that raises the exception
except ValueError:
#turn it into something useful