← Back to C# Course | Chapter 10: Exception Handling | Lesson 1 of 6

try / catch / finally

In this page:

  1. try / catch / finally

try / catch / finally

A try block contains code that might throw an exception; a matching catch block handles it if one occurs. finally runs afterward regardless of whether an exception was thrown, making it the right place for cleanup code. Execution jumps straight from the point of the exception to the nearest matching catch.

Note: finally runs even if the try or catch block contains a return statement.

Example: try / catch / finally

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            int[] numbers = { 1, 2, 3 };
            Console.WriteLine(numbers[5]);
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine("Caught: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Cleanup complete");
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.