Reputation: 21
Is either of these methods proper? I am trying to get a general 'this script failed' type of exception to send a message to the log table. the script is run from command line initiate by an ansible play (shell module with async:0 poll: 0). Throughout main() and the various functions, I send status messages to the log table, but I need to know if the script fails at all.
main()
try:
logic()
if more code:
more_logic()
except:
send_error()
or isit better like this:
if __name__ == "__main__":
try:
main()
except:
send_error()
Thanks
Upvotes: 2
Views: 1144
Reputation: 77902
Well, the main (no pun intented xD) difference between your two snippets is that in the second version the try/except block will only be setup when you run your script as a script - not when you import it as a module and call the main()
function. Whether this is what you want or not depends on your concrete use case, so only you can tell which is more appropriate here.
Now there IS an issue in both cases: you're using a bare except clause (which might actually catch more than you expect), and totally ignore the exception itself so you loose all the useful debugging informations about what went wrong and where, so what you want here is actually:
try:
some_code_that_may_raise()
except Exception as e:
log_the_error(e)
Note FWIW that Python has a very comprehensive (even if not specially easy to learn) logging
package that knows how to format exceptions tracebacks etc. This is incredibely useful in practice so it's really worth investing a few days to learn how to properly use it.
Upvotes: 1