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.

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

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

This post is divided into several sections:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Let’s start.

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 built-in support to handle these exceptions by using a try-catch block of code:

try
{
    // expressions that could cause an exception
}
catch(Exception ex)
{
    // handle exception
}

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 that prints out the square root of the integer number entered by the user:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your number: ");
        int num = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine(Math.Sqrt(num));
    }
}

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:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Enter your number: ");
            int num = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine(Math.Sqrt(num));
            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"There is something wrong in our application, please look at this message: {ex.Message}");
            Console.ReadKey();
        }
    }
}

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.

Let’s see how we can use them in our code:

public class Program
{
    public static void Main()
    {
        try
        {
            //Code in here that could cause an exception
        }
        catch (DivideByZeroException ex)
        {
            Console.Write("Cannot divide by zero. Please try again.");
        }
        catch (InvalidOperationException ex)
        {
            Console.Write("Not a valid number. Please try again.");
        }
        catch (FormatException ex)
        {
            Console.Write("Not a valid number. Please try again.");
        }
        catch(Exception ex)
        {
            Console.Write("Any exception that previous catch blocks didn’t handle.");
        }

        Console.ReadKey();

    }
}

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#

Conclusion

Excellent.

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

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

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!