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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With