简体   繁体   中英

Can I raise an exception if a statement is False?

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

I want to modify the above code to check the value of content to see if it contains string. I thought of using if 'stuff' in content: or regular expressions, but I don't know how to fit it into the try ; so that if the match is False , it raises the exception. Of course, I could always just add an if after that code, but is there a way to squeeze it in there?

Pseudocode:

try:
    content = my_function()
    if 'stuff' in content == False:
        # cause the exception to be raised
except:
    exit('Could not complete request.')
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))

If your code can have several possible exceptions, you can define each with a specific value. Catching it and exiting will then use this error value.

To raise an exception, you need to use the raise keyword. I suggest you read some more about exceptions in the manual . Assuming my_function() sometimes throws IndexError , use:

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

Also, you should never use just except as it will catch more than you intend. It will, for example, catch MemoryError , KeyboardInterrupt and SystemExit . It will make your program harder to kill ( Ctrl + C won't do what it's supposed to), error prone on low-memory conditions, and sys.exit() won't work as intended.

UPDATE: You should also not catch just Exception but a more specific type of exception. SyntaxError also inherits from Exception . That means that any syntax errors you have in your files will be caught and not reported properly.

You can raise an exception with raise if that's what you're asking:

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

Note that you need to decide what kind of exception to raise. Here I raised ValueError. Likewise, you shouldn't use a bare except , but should use except ValueError or the like, to catch only the type of error you want to handle. In fact, in this case that's especially important. You presumably want to distinguish between a real error raised by my_function and the "stuff not in content" condition that you're testing.

A nicer way to do this would be just to assert that the key is there:

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

If the assertion is not true, an AssertionError will be raised with the given message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM