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

try / catch / finally

try, catch, and finally are a safety net: try something risky, catch the problem if it falls, and finally clean up no matter what. It keeps your program from crashing.

In this page:

  1. try / catch / finally
Syntax
csharp
try
{
    // code that might throw
}
catch (ExceptionType ex)
{
    // handle the error
}
finally
{
    // always runs
}

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");
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Catching Exception and leaving the catch block empty, which hides real errors.
  2. Putting a general catch (Exception) before specific catches, which is a compile error.
  3. Putting code that must always run in the try instead of finally.
🔒

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.