CLEAN CODE & REFACTORING

Seven Techniques to Master Error Handling

Guide for better Error Handling: principles, recommendations, and techniques on how to work with exceptions in C#.

Daniel Rusnok
The Startup
Published in
4 min readJun 14, 2020

--

Photo by Dana Vollenweider on Unsplash

Error handling is an essential part of a programmer’s life. Inputs can be abnormal, and applications can fail. We need to make sure that our code does what it’s supposed to do.

In this article, I will outline the techniques and recommendations that you can use to write code that handles errors and stays clean. For code examples, I will use C# 8.0.

Don’t Return and Pass Null

The best approach to handling an exception is to avoid making them. Nothing good comes from returning or passing null. NullReferenceException is the most thrown exception in C#, and we shouldn’t support anymore. Naturally, if you are in need to return or pass default value, then pass the default value.

  • If you need to return the default value of string— just return string.Empty.
  • If you need to return the default value of List — just return Enumerable.Empty<T>().
  • If you need to return the default value of your class — just create the default representation of it.

--

--

Daniel Rusnok
The Startup

Senior Software Developer. Loving to gain & share knowledge. Focused on Microsoft technologies like Azure, .NET Core & C#. Software Architecture enthusiasist.