Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.')
like image 791
user1417933 Avatar asked Nov 12 '12 08:11

user1417933


2 Answers

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.

like image 65
kichik Avatar answered Sep 20 '22 10:09

kichik


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.

like image 32
eumiro Avatar answered Sep 23 '22 10:09

eumiro