In this article, we are going to learn how to use try-catch blocks while Handling exceptions in C#. Moreover, we are going to learn how to use multiple catch blocks to handle more specific exceptions in our code.

For the complete navigation of this series check out: C# Back to Basics.

If you want to download the source code for our examples, you can do that from here Handling Exceptions in C# Source Code.

This post is divided into several sections:

What is Exception

The exception is a problem that appears unexpectedly in our code while we develop our project. That’s why we call these exceptions unhandled exceptions. If they are not handled, they will cause our application to stop working and will throw one of the exception messages. That is not something we want in our code.

Try-Catch Block

C# provides us with a built-in support to handle these exceptions by using a try-catch block of code:

In the try block, we write our code and the catch block will handle all the exceptions that could arise in the try block. This way our program won’t stop at all and we can show some meaningful message to a user.

Let’s see how our program works without and with exception handling.

Example 1: Create an application which prints out the square root of the integer number entered by the user:

This code is going to work just fine if a user enters an integer number, but look at what is going to happen if a user enters a string:

Unhandled exception - Handling Exceptions in C#

We see that our application has stopped working. This is very bad for the user experience. So, let’s implement the same code but with the try-catch block:

If we check out the result now:

Handled exception - Handling Exceptions in C#

As we can see, our app has not stopped and we have a nice readable message for our user, which provides a much better user experience than the previous example.

Specific Exceptions

C# has its own set of specific exceptions which we can use in our application. Some of them are: NullReferenceException, ArgumentOutOfRangeException, InvalidCastException, FileNotFoundException, DevideByZeroException, FormatException, InvalidOperationException etc.

We can use them in this way:

It is very important to place the specific catch blocks before the global catch block, otherwise, our compiler will complain:

Invalid Exception - Handling Exceptions in C#



Now we know how to write a safe code and how to handle errors in our app.

In a next post, we are going to talk about Access Modifiers in C#.

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.