Exception Handling in C#: Best Practices

Exception handling in C# can significantly benefit from improved code readability and maintainability.

Sukhpinder Singh | C# .Net
.Net Programming
Published in
3 min readJul 2, 2023

--

Photo by Shahadat Rahman on Unsplash

Introduction

When it comes to handling exceptions, developers often face choices that impact code structure and understandability. One such decision involves using exception filters v/s alternative approaches like lambda expressions or closures.

The article demonstrates these options, focusing on their effects on code comprehension and maintainability. The aim is to empower developers to make informed decisions regarding exception handling in C# through examples and best practices.

Using Exception Filters

Starting from C# 6.0, exception filters provide a concise and expressive way to handle exceptions selectively. By utilizing the catch statement with a when clause, developers can specify conditions to handle specific exception types. For instance:

catch (Exception ex) when (ex is ... || ex is ... || ex is ...)
{
// Handle the exception
}

Although this approach offers compact code, some developers find it less visually appealing and argue that it may hinder code comprehension, especially when the condition spans multiple lines.

--

--

Sukhpinder Singh | C# .Net
.Net Programming

.Net Developer - Editor at .Net Programming with ~48K views per month, Looking for C# writers. Link: https://medium.com/c-sharp-programming