​How to: C# Exception Handling – Best Practices

There it is, a pesky exception! Many new to the industry find C# exception handling a daunting task, but only a few know it doesn’t have to be a challenging endeavor. Follow this guide and you’ll be a pro at it in no time.

C# Exception Handling skills are necessary if you want to program in this language

What Are Exceptions?

Before getting started, it’s important to know what are exceptions. They are defined as a type of error that occurs during the execution of an application, and are often unexpected. These exceptions happen for a wide variety of reasons, and applications use handling logic to take care of them as they happen.

They allow the app to transfer control from one part of a code to another. During the transfer (throw) the current flow of the code is interrupted and thrown back into what is called a parent try catch block.

What Is C# Exception Handling?

C# handling is done with four keywords, try, catch, finally, and throw. To better explain:

  • Try – A try block encapsulates a region of code. Should there be an exception in that code, it will then be handled by a corresponding catch.
  • Catch – Once the exception occurs, the catch block of code executes. This is where you come in to either take care of it, log it, or ignore it.
  • Finally – Consider this your ultimate judge on exceptions. You can execute certain code whether an exception is thrown or not, such as disposing of it.
  • Throw – This keyword is used to create a new exception. You would use this to bubble up a try-catch-finally block.

You will use the try and catch keywords to define try-catch boxes as they handle exceptions to ensure user errors, crashes, and unhandled issues do not occur. The need to define them comes from the various reasons an exception may occur, such as a null URL or failed script.

Exception Filters

You can have more control over these blocks with exception filters, allowing you to fine tune how you handle them and which one’s you want to catch. For instance, you may wish to only catch specific types of Web Exceptions as opposed to every single one that occurs. They make the process a whole lot easier.

Common Exceptions in .NET

You can expect to see some of these occur in your application’s code.

  • System.NullReferenceException
  • System.IndexOutOfRangeException
  • System.IO.IOException
  • System.Net.WebException
  • System.Data.SqlClient.SqlException
  • System.StackOverflowException
  • System.OutOfMemoryException
  • System.InvalidCastException
  • System.InvalidOperationException
  • and System.ObjectDisposedException

C# Exception Logging Best Practices

Handling these exceptions requires logging them in a library so you can keep a good record of what had occurred. Using a program such as NLog or Serilog, you can log every exception to a created file as well as send them to various other targets like a database or error monitoring service.

Without logging exceptions, it becomes an impossible task to find issues within your code. Contextual details including what customer experienced the exception and key variables being used will also need to be logged. However, logging these to a file is not quite enough.

Logging exceptions with an error monitoring service offers additional benefits such as unique identification, email alerts, and quickly searching for exceptions across all servers and applications.

Now You Know!

C# exception handling isn’t as hard as it seems, and with a little practice you’ll be a pro at it in no time. Combining your new skill with an error monitoring service is the best way to keep the code for any application running smoothly. Whether you are a developer yourself, or a company with a development team, use these best practices for every app in production and your users will remain satisfied.