On Error Handling
Karan Chawla / April 19, 2021
1 min read
Error handling is important, but if it obscures logic, it's wrong. It should be added cleanly such that it doesn't make the code harder to understand and reason about.
It's better to throw exceptions than return error codes if your language permits. Return codes add to the complexity of the code, make the libraries hard to use by adding complexity, add to the documentation upkeep, and are error-prone.
try-catch-finally blocks add scope to the code.
try blocks are like transactions;
catch block has to leave the program in a consistent state no matter what happens in the
Start your implementation with
try-catch block. Write tests that force exceptions, and then add behavior to your handler to satisfy your tests. This will cause you to build the transaction scope of the try block first and will help you maintain the transaction nature of that scope.
Provide context with exceptions — Each exception should mention the operation that failed and the type of failure. If there's logging in the application, pass along enough information to be able to log the error in the
Subscribe to the newsletter
Get emails from me about future of technology, philosophy, and human behavior.