如果语句为False,我可以引发异常吗?

时间:2012-11-12 08:46:11

标签: python exception try-catch

try:
    content = my_function()
except:
    exit('Could not complete request.')

我想修改上面的代码来检查content的值,看它是否包含字符串。我想过使用if 'stuff' in content:或正则表达式,但我不知道如何将它放入try;因此,如果匹配为False,则会引发异常。当然,我总是可以在代码之后添加if,但有没有办法在那里挤压它?

伪代码:

try:
    content = my_function()
    if 'stuff' in content == False:
        # cause the exception to be raised
except:
    exit('Could not complete request.')

4 个答案:

答案 0 :(得分:7)

try:
    content = my_function()
    if 'stuff' not in content:
        raise ValueError('stuff not in content')

    content2 = my_function2()
    if 'stuff2' not in content2:
        raise ValueError('stuff2 not in content2')

except ValueError, e:
    exit(str(e))

如果您的代码有几个可能的例外,您可以使用特定值定义每个例外。然后捕获并退出将使用此错误值。

答案 1 :(得分:5)

要引发异常,您需要使用raise关键字。我建议您在manual中阅读更多有关例外的内容。假设my_function()有时会抛出IndexError,请使用:

try:
    content = my_function()
    if 'stuff' not in content:
        raise ValueError('stuff is not in content')
except (ValueError, IndexError):
    exit('Could not complete request.')

此外,你应该从不只使用except,因为它会比你想要的更多。例如,它会捕获MemoryErrorKeyboardInterruptSystemExit。这将使你的程序更难杀死( Ctrl + C 不会做它应该做的事情),在低内存条件下容易出错,sys.exit()不会按预期工作。

更新:您也不应仅仅捕获Exception,而是更具体的异常类型。 SyntaxError也继承自Exception。这意味着您的文件中存在的任何语法错误都将被捕获,并且无法正确报告。

答案 2 :(得分:1)

如果您要问的话,可以使用raise引发异常:

if 'stuff' not in content:
    raise ValueError("stuff isn't there")

请注意,您需要确定要引发的异常类型。在这里我提出了ValueError。同样,您不应该使用裸except,而应使用except ValueError等来捕获您想要处理的错误类型。事实上,在这种情况下,这一点尤其重要。您可能想要区分my_function引发的实际错误和您正在测试的“内容不符合条件”。

答案 3 :(得分:0)

更好的方法是断言密钥在那里:

assert 'stuff' in content, 'Stuff not in content'

如果断言不正确,将会使用给定的消息引发AssertionError