Top 10 Dotnet Exception Anti-Patterns in C#
Identifying (and fixing) the 10 most common C# exception mistakes I see
As a programming instructor and former software engineer / software engineering manager I have seen a lot of mistakes around exception management in dotnet code.
In this article we’ll explore the top 10 mistakes I see new and seasoned developers make with exception management in dotnet source code. These principles should be valid for all dotnet languages, but examples will be provided in C#.
Also note that some of these are so common you’ll also see them on my list of common dotnet gotchas.
#1: Not Catching Exceptions
The first major mistake I see people make is not accounting for exceptions that may occur in their code.
While there are plenty of exceptions that are the fault of the developer (
InvalidOperationException, etc.), there are exceptions that no developer can prevent from occurring.
For example, when working with files, it’s possible that the needed file does not exist, the user doesn’t have permission to open it, the file is corrupt or locked, or the hard drive runs out of disk space (among other potential problems). All of these issues can result in exceptions that would be unrealistically hard for developers to prevent from occurring.
Other common things that might fail include:
- Connecting to external APIs
- Connecting to databases
- Executing SQL statements
- Working with the operating system
- Requesting resources over the internet
- Working with hardware devices such as cameras or microphones
- Relying on an active internet connection
All of these scenarios are things that the programmer should account for by adding a catch clause for a specific exception that may occur.