Categories: Basic C#

C# Back to Basics – Handling Exceptions in C#

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:

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 which 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:

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:

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:

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:

Conclusion

Excellent.

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.

Marinko Spasojevic

View Comments

Share
Published by
Marinko Spasojevic
Tags: ArgumentOutOfRangeException C# DevideByZeroException FileNotFoundException FormatException handling exceptions InvalidCastException InvalidOperationException NullReferenceException try-catch try-catch block

Recent Posts

  • Web Development

Consuming a GraphQL API with Angular

In the previous article, we have created an ASP.NET Core application to consume a GraphQL API. But we don't have…

6 days ago
  • Web Development

Consuming a GraphQL API with ASP.NET Core

In the previous article, we have finished creating mutations in the GraphQL application, thus finishing the GraphQL integration in ASP.NET…

2 weeks ago
  • Web Development

GraphQL Mutations in ASP.NET Core

GraphQL mutations are actions which we use to Add, Update and Delete data from a database. Until now, we have…

3 weeks ago
  • C#
  • Web Development

Advanced GraphQL Queries, Error Handling, Data Loader

In the previous article, we have learned about the GraphQL integration with the ASP.NET Core application. We have created our…

4 weeks ago
  • Web Development

Getting Started with GraphQL in ASP.NET Core

In this article, we are going to learn how to set up GraphQL in ASP.NET Core application. We are going…

1 month ago
  • C#
  • Design Pattern

C# Design Patterns – Strategy

The Strategy design pattern is a behavioral design pattern which allows us to define different functionalities, put each functionality in…

1 month ago