3 ms·
I disagree with most of this advice. I think Google's Python Style Guide provides exception guidance that leads to clearer code.[0] I agree with Animats's comm
by mtlynch 5y ago
I disagree with most of this advice. I think Google's Python Style Guide provides exception guidance that leads to clearer code.[0]
I agree with Animats's comment[1] about not catching the base Exception class, and the Google guidelines explicitly prohibit this, except at the outermost scope. One obvious flaw in catching Exception is if that if the user hits Ctrl+C to kill the application, but the code happens to be executing the ReceiptService at the time, the app will confusingly raise a ReceiptGenerationFailed exception instead of KeyboardInterrupt. (Edit: this isn't true, thanks to child comment for correction)
The final code snippet shows four function calls within the same try even though the functions throw a disjoint set of exceptions. It's unclear to a reader at the callsite what exception handlers corrrelate with which functions.
except OrderAlreadyInProgress as e:
logger.info("Aborting emission request because it is already in progress!")
return {"order_id": order_id, "order_status": e.order_status.value}
To me, it feels sinful to use an exception to effectively "return" a value that the caller needs. I only use member fields in the exception to describe what went wrong. The original "bad" version of the code returned this information to the caller without raising an exception, and that felt more intuitive to me.
else:
return {"order_id": order_id, "order_status": order_status.value}
I don't understand the purpose of the else at the end. I would just write the return within the try as:
return {"order_id": order_id, "order_status": status_service.get_order_status(order_id) }
[0] https://google.github.io/styleguide/pyguide.html https://google.github.io/styleguide/pyguide.html
[1] https://news.ycombinator.com/item?id=27217301 https://news.ycombinator.com/item?id=27217301
- tmarice 5y agohttps://docs.python.org/3/library/exceptions.html#KeyboardInterrupt https://docs.python.org/3/library/exceptions.html#KeyboardIn... `KeyboardInterrupt` inherits from `BaseException` instead of `Exception` exactly in order to avoid this situation.
- mtlynch 5y agoOh, thanks for the correction. I remember running into this myself, but I must have done: except:
- deleted 5y ago[deleted]