Exceptions in .Net

In my professional activity in different areas of the software development, I’ve got quite often the question, from less experienced and even senior developers: how to approach error handling in case of a particular, or even more general scenario? We have exceptions, right? We have try-catch (eventually finally) statements, or similar, in different programming languages it should be pretty straight forward to catch exceptions and display a message to the user of the application. Or, maybe even better, we can hide any exception that happen to be thrown and everybody should be happy, right?!
The above mentioned approach is actually wrong for many reasons. It may work for small sample applications but is far from being the way to go for professional software solutions.
The error handling always depend on more than one factor, the most important being the programming language, the technology stack that it’s used (frameworks, libraries, single vs multi-threaded, etc.) and application architecture (monolithic, distributed, microservices’ based, number of tiers etc.). So, in order o be able to take the right decision in a particular case regarding how to handle the possible erroneous situations, there is required to gather a good understanding about all the 3 main areas that I’ve mentioned about.
In order to reduce the scope, I’ll focus on .Net library / runtime (mscorlib[1]) and, later on, I’ll approach the best scenarios for error handling in case of different types of applications and/or services (for that Microsoft provides different frameworks).
So, I’ve used both terms, errors and exceptions and that was not a mistake or an intention to consider them as synonyms. In some regard, there is a conceptual overlap in a way that an exception can be thrown when an error has occurred, but this is valid for cases when there is some integration with an external library/process (usually unmanaged or native code[2]) that doesn’t support exceptions or has no way to pass them to the caller (via Marshalling[3], Serialization[4], etc.)

References:

  1. “Multi-language Standard Common Object Runtime Library”, C# 7.0 in a Nutshell, Ben Albahari, Joseph Albahari, O’Reilly Media, Inc., October 2017, ISBN: 9781491987643
  2. About Managed / Unmanaged code…
  3. https://en.wikipedia.org/wiki/Marshalling_(computer_science)
  4. https://en.wikipedia.org/wiki/Serialization

 

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.