Re:Handling exceptions in Python like a pro
by tmarice on Thursday May 20, 2021 @03:56AM
(#27218569)
https://docs.python.org/3/library/exceptions.html#KeyboardIn...
`KeyboardInterrupt` inherits from `BaseException` instead of `Exception` exactly in order to avoid this situation.
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.
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. I don't understand the purpose of the else at the end. I would just write the return within the try as: [0] https://google.github.io/styleguide/pyguide.html[1] https://news.ycombinator.com/item?id=27217301