C# Beginners – Try/Catch/Finally

C# Beginners – Try/Catch/Finally; covers using a try/catch block to avoid program crashes in C#. This tutorial follows on from if/else and switch statements. Before attempting this tutorial, you should have chosen an IDE and be comfortable with it. Additionally, you should be familiar with the essential data types and conditional statements for making a selection. If this is not the case, please see previous tutorials in this series. A video version of this tutorial is available at the bottom of the post or here.

What is Try/Catch/Finally – C# Beginners

In plain English, a try/catch/finally block says; try this; if it causes a crash (exception), catch it and do something about it. Then, a third section called finally can be included, which will run whether or not there is an exception. One of the most common causes of exceptions for new programmers is casting from a string to a number type, such as an integer.

See the example below.

Console.WriteLine("Please type a number then press enter.");
string? userInput = Console.ReadLine();
int number = int.Parse(userInput);
Console.WriteLine(number.ToString());

Give the code in the example above a try. You will find that any slight mistakes, such as a space character before or after the number, will cause a crash. Similarly, typing “ten” rather than “10” will cause an exception and the program to crash.

Handling the exception

This error can be handled with a try/catch block. See the example below.

Console.WriteLine("Please type a number then press enter.");
string? userInput = Console.ReadLine();
try
{
    int number = int.Parse(userInput);
    Console.WriteLine(number.ToString());
}
catch (Exception exception)
{
    Console.WriteLine("Sorry the following exception occured: \n" + exception);
}

Example without an exception.

Example with an exception.

Please type a number then press enter.
ten
Sorry the following exception occured: 
System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Int32.Parse(String s)
   at Program.<Main>$(String[] args) in /home/sara/src/CodingTutorials/C#/Try-Catch-Finally/Try-Catch-Finally/try-catch-fin/Program.cs:line 7

Using Finally

The Finally block is not necessary but can be helpful in some circumstances. It will always run; exceptions make no difference. Try the code below and experiment with the results. See the example below.

Related Articles – C# Beginners – Try/Catch/Finally

Console.WriteLine("Please type a number then press enter.");
string? userInput = Console.ReadLine();
try
{
    int number = int.Parse(userInput);
    Console.WriteLine(number.ToString());
}
catch (Exception exception)
{
    Console.WriteLine("Sorry the following exception occured: \n" + exception);
}
finally
{
    Console.WriteLine("I always run, exception or not!");
}

Try running this code in the same way as the first example. The output will be similar, but both cases will include the code inside the Finally block.

Example without an exception.

Please type a number then press enter.
10
10
I always run, exception or not!

Example with an exception.

Please type a number then press enter.
ten
Sorry the following exception occured: 
System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Int32.Parse(String s)
   at Program.<Main>$(String[] args) in /home/sara/src/CodingTutorials/C#/Try-Catch-Finally/Try-Catch-Finally/try-catch-fin/Program.cs:line 7
I always run, exception or not!

Video Version

Related Articles – C# Beginners – Try/Catch/Finally

Related Post

8 thoughts on “C# Beginners – Try/Catch/Finally

Leave a Reply

Your email address will not be published. Required fields are marked *