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:

  1. Avoid creating your own custom exceptions if possible. Encourage to use the built in ones.
  2. 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.
  3. 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

  1. Stack trace not preserved
  2. 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?

  1. Before writing your own exceptions, search and use the common, well-designed, existing ones.
  2. 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.
  3. Custom exceptions must be designed with care.

Write a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.