2

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

2
  • The effect will be the same. Commented Apr 23, 2020 at 10:07
  • It makes no difference according to your code. however, it might be different while there are other methods calls in if _name_ == "_main_": Commented Apr 23, 2020 at 10:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.