Menu
Coddy logo textTech

Finally Block

Part of the Logic & Flow section of Coddy's C# journey — lesson 27 of 66.

The finally block contains code that always executes, whether an exception occurs or not, even if there's a return statement in the try or catch blocks.

Create a basic try-catch-finally structure:

try
{
    // Code that might throw an exception
    int result = 10 / 2;
    Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
    // Code that handles the exception
    Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
    // Code that always executes
    Console.WriteLine("This always executes");
}

The finally block is useful for cleanup tasks like closing files or database connections:

System.IO.StreamReader file = null;
try
{
    file = new System.IO.StreamReader("data.txt");
    string content = file.ReadToEnd();
    Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
    Console.WriteLine("File not found.");
}
finally
{
    // Always close the file, even if an exception occurred
    if (file != null)
    {
        file.Close();
    }
}
challenge icon

Challenge

Easy

Create a method named ProcessData that:

  1. Takes a string parameter representing a filename
  2. Attempts to open the file and read its contents
  3. Writes the contents to the console
  4. Properly cleans up resources using a finally block
  5. Handles FileNotFoundException and IOException

If the file can't be found, print: "ERROR: File not found: [filename]"

If another IO error occurs, print: "ERROR: Could not read the file: [error message]"

Always print "File operation completed." in the finally block, whether an exception occurred or not.

Try it yourself

using System;
using System.IO;

class Program
{
    public static void ProcessData(string filename)
    {
        // Write your code here
    }
    
    static void Main(string[] args)
    {
        string filename = Console.ReadLine();
        ProcessData(filename);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow