Categories: BasicC#

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: ArgumentOutOfRangeExceptionC#DevideByZeroExceptionFileNotFoundExceptionFormatExceptionhandling exceptionsInvalidCastExceptionInvalidOperationExceptionNullReferenceExceptiontry-catchtry-catch block

Recent Posts

  • C#
  • Design Pattern

C# Design Patterns – Decorator

In this article, we are going to talk about another structural C# design pattern, the Decorator Design Pattern. We are…

1 day ago
  • C#

Basic Tips and Tricks to Boost Productivity in Visual Studio

Visual Studio is a Microsoft IDE that is used by many developers worldwide every day. It is a great tool…

1 week ago
  • C#
  • Design Pattern

C# Design Patterns – Composite

The Composite design pattern is a structural design pattern which allows us to compose objects into a tree structure and…

2 weeks ago
  • C#
  • Design Pattern

C# Design Patterns – Adapter

The Adapter design pattern is a creational pattern which allows incompatible interfaces to work together. By doing so, we allow…

3 weeks ago
  • C#
  • Design Pattern

C# Design Patterns – Singleton

The Singleton is a creational design pattern which allows us to create a single instance of an object and to…

4 weeks ago
  • C#
  • Design Pattern

C# Design Patterns – Factory Method

The Factory method is a creational design pattern which provides an interface for creating objects without specifying their concrete classes.…

1 month ago