Tips and Tricks

How to catch exceptions in C#

tips_tricks

In this article, we will demonstrate how to catch exceptions thrown in your C# code.

In the following example, we are using a simple Console application, which asks from user his/her age, and shows it on screen.

We use a Try-Catch block to handle possible errors.

First, we are catching a specific exception, FormatException, which will output a message, saying that the age entered is not a valid number. This might happen in case user enters a value that could not be converted into integer type.

Finally, we will catch all other exception that might be thrown, returning the Type and the Message of the Exception.

Write("What is your age? ");
string? input = ReadLine();
try
{
int age = int.Parse(input);
WriteLine($"You are {age} years old.");
}
catch (FormatException)
{
WriteLine("The age you entered is not a valid number format.");
}
catch (Exception ex)
{
WriteLine($"{ex.GetType()} says {ex.Message}");
}