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#.
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 returnstring.Empty.
- If you need to return the default value of
List
— just returnEnumerable.Empty<T>().
- If you need to return the default value of your class — just create the default representation of it.