Finally Block in C#
What is the Finally Block in C#?
The finally block in C# is used to execute code after a try and catch block, regardless of whether an exception occurs. It is commonly used for resource cleanup, such as closing file streams, database connections, or releasing memory.
Key Features of Finally Block
- Executes after the
tryandcatchblocks, whether an exception occurs or not. - Ensures resource cleanup like closing files, releasing memory, or disconnecting from databases.
- Cannot be skipped even if a return statement is used inside the
tryblock. - Used with
tryandcatch, but not mandatory.
Example: Using the Finally Block
The following example demonstrates how a finally block executes regardless of whether an exception occurs.
Example: Handling Exception with Finally Block
using System;
class Program
{
static void Main()
{
try
{
int num1 = 10, num2 = 0;
int result = num1 / num2; // This will cause a DivideByZeroException
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Exception Caught: {ex.Message}");
}
finally
{
Console.WriteLine("Execution completed, cleaning up resources.");
}
}
}
// Output:
// Exception Caught: Attempted to divide by zero.
// Execution completed, cleaning up resources.
The finally block ensures that the cleanup message is always displayed, even if an exception occurs.
Using Finally Block for Resource Cleanup
The finally block is often used to close files, release memory, or disconnect databases.
Example: Closing a File Using Finally Block
using System;
using System.IO;
class Program
{
static void Main()
{
StreamReader reader = null;
try
{
reader = new StreamReader("sample.txt");
Console.WriteLine(reader.ReadToEnd());
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File Not Found: {ex.Message}");
}
finally
{
if (reader != null)
{
reader.Close();
Console.WriteLine("File closed.");
}
}
}
}
// Output (if file not found):
// File Not Found: Could not find file 'sample.txt'.
// File closed.
The finally block ensures that the file is closed, whether an exception occurs or not.
Finally Block Execution with Return Statement
The finally block executes even if the try block contains a return statement.
Example: Finally Block Executing After Return
using System;
class Program
{
static void Main()
{
Console.WriteLine(MethodWithFinally());
}
static int MethodWithFinally()
{
try
{
Console.WriteLine("Inside Try Block");
return 10;
}
finally
{
Console.WriteLine("Finally Block Executed");
}
}
}
// Output:
// Inside Try Block
// Finally Block Executed
// 10
Even though the try block has a return statement, the finally block executes before the method returns.
Best Practices for Using Finally Block
- Use the
finallyblock to release resources like file handles and database connections. - Avoid putting return statements inside a
finallyblock, as it can override exceptions. - Do not place critical business logic in the
finallyblock, as it should be for cleanup only. - Use
usingstatements as an alternative for automatic resource management.