[Tutor] Logging exceptions, but getting stderr output instead
Steven D'Aprano
steve at pearwood.info
Sun May 29 22:17:54 EDT 2016
On Wed, May 25, 2016 at 02:11:01PM -0400, Alex Hall wrote:
> As a quick aside, is there an easy way to halt script execution for some
> exceptions? Right now, catching them means that execution continues, but I
> sometimes want to log the problem and then abort the script, as the error
> means it shouldn't continue. Thanks.
In general you shouldn't fill your code with exception handling code if
you can avoid it. You should only catch exceptions that you can handle and
recover from. It's okay to log them right there, but since it's a
recoverable error it should be a warning, not an error.
You should generally not catch fatal errors (except once, see below). If
you must catch them, to decide whether or not they are fatal, then don't
log them at the point you caught it, just re-raise using the base
"raise" statement.
Finally, you should wrap your entire script in a single try...except to
catch all the fatal exceptions in one go, log them, and exit. One way is
this:
# Run the main script.
if __name__ == '__main__':
try:
main()
except Exception:
logging.exception("message")
sys.exit(error_code)
which will log an Error with "message", and the details of the exception
including the traceback before exiting.
An alternative to a try...except block will be to set the excepthook
before running main().
https://docs.python.org/3/library/sys.html#sys.excepthook
As always, it's okay to break these rules carefully and after giving
them due thought. But if you find yourself calling sys.exit dozens of
times from wildly-separate parts of your code, you're probably doing it
wrong.
--
Steve
More information about the Tutor
mailing list