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
EasyCreate a method named ProcessData that:
- Takes a string parameter representing a filename
- Attempts to open the file and read its contents
- Writes the contents to the console
- Properly cleans up resources using a finally block
- 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.
Cheat sheet
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.
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();
}
}
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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety