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.')
To raise an exception, you need to use the
raisekeyword. I suggest you read some more about exceptions in the manual. Assumingmy_function()sometimes throwsIndexError, use:Also, you should never use just
exceptas it will catch more than you intend. It will, for example, catchMemoryError,KeyboardInterruptandSystemExit. It will make your program harder to kill (Ctrl+C won’t do what it’s supposed to), error prone on low-memory conditions, andsys.exit()won’t work as intended.UPDATE: You should also not catch just
Exceptionbut a more specific type of exception.SyntaxErroralso inherits fromException. That means that any syntax errors you have in your files will be caught and not reported properly.