Python – Ways of Handling Exceptions
Another step in my Python journey, this time I learn about exceptions – raising and handling exceptions. The syntax is simple. I can reason about them because they look familiar with C#.
try:
// Do something
except ValueError as e:
// Do something
except KeyError:
// rethrow the original exception
raise
finally:
// Clean up. Code that will run regardless of
What interesting is the Python philosophies about exceptions:
- Avoid creating your own custom exceptions if possible. Encourage to use the built in ones.
- Error codes are silence, exceptions are not. It is more about design/code principle. Instead of returning an error code, let the application throw exceptions or fail.
- Handle exceptions that your function are expecting or capable of.
I have seen applications where custom exceptions are defined. If well-designed, they serve good purpose. Otherwise, they cause some trouble – lost in translation
- Stack trace not preserved
- Consumers catch custom exceptions and it is hard to handle it correctly. Why? How could it know what the actually root cause? – the inner exception part.
While writing this, a retrospective moment came up in my head. I have not seen, I have not documented much, the exceptions in code. Except framework code, where they always document what exceptions might be raised. In business applications, for applications I have seen/written so far of course, we do not have a habit of documenting possible exceptions.
Let weight it as essential habit and practice.
So what have I learn to help me becoming a better developer?
- Before writing your own exceptions, search and use the common, well-designed, existing ones.
- Document your API with possible exceptions. Eventually, exceptions are also output from your API. Consumers need to be aware and have a plan to handle them properly.
- Custom exceptions must be designed with care.