Reputation: 7302
What is a Pythonic way to not have duplicated code for exception handling?
In a real code base, it is not 2 / 0
, but reading or writing from an async socket, and I have more exceptions to catch, ConnectionResetError, BrokenPipeError, and TimeoutError.
I do not want to duplicate on code for exception handling, so I would appreciate an example. What is a Pythonic way to do it?
This is the current solution that I have:
try:
2 / 0
except Exception as e:
exception_handling_1(e)
def exception_handling_1(e):
print(f'{type(e)=} {e=}')
if isinstance(e, ValueError):
print("Caught a ZeroDivisionError")
else:
raise e
Upvotes: 0
Views: 47
Reputation: 7206
Usually, I solve this by using abstraction. You put the code that could generate these errors in a handler or service class, where you only need to write the error handling once and then use that class wherever it is needed. In your (very unreal) example this could look like this:
class DivisionService:
def divide(a: float, b: float) -> float | None:
"""Calculate a / b"""
try:
return a / b
except ZeroDivisionError:
print("Caught a ZeroDivisionError")
return None
if __name__ == "__main__":
division_service = DivisionService()
division_service.divide(2, 0)
Which is of course way over the top for something as simple as doing division, but can be quite appropriate when e.g. contacting a remote service, handling possible connection errors and parsing the returned data, which may also fail.
Using a class instead of a function allows you to also handle state (e.g. a base_url
, shared headers, a client / connection object, ...).
Upvotes: 2