try, catch, and finally Blocks

Handling errors gracefully in C#

Posted by Rodrigo Castro on November 30, 2024

C# uses try, catch, and finally blocks to help you handle exceptions (errors) safely.

🛠️ try Block

Put code that might fail here.

1
2
3
4
try
{
    int n = int.Parse("oops"); // Will throw an exception!
}

🛡️ catch Block

Handle the error.

1
2
3
4
5
6
7
8
try
{
    int n = int.Parse("oops");
}
catch (FormatException)
{
    Console.WriteLine("Not a number!");
}

🔚 finally Block

Always runs whether or not there was an error. Useful for cleanup.

1
2
3
4
5
6
7
8
9
10
11
12
try
{
    // risky code
}
catch
{
    // handle error
}
finally
{
    Console.WriteLine("Done!");
}

💡 Try It!

Ask the user for a number, handle the error, and always print “Goodbye!”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try
{
    Console.Write("Enter a number: ");
    int n = int.Parse(Console.ReadLine());
    Console.WriteLine($"You entered {n}");
}
catch
{
    Console.WriteLine("That was not a valid number.");
}
finally
{
    Console.WriteLine("Goodbye!");
}

Next: Throwing your own exceptions!