Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is finally statement in C#?
The finally statement in C# is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
The error handling blocks are implemented using the try, catch, and finally keywords. The finally block is guaranteed to execute, making it ideal for cleanup operations like closing files, database connections, or releasing resources.
Syntax
Following is the syntax for the finally statement −
try {
// code that might throw an exception
} catch (ExceptionType e) {
// exception handling code
} finally {
// cleanup code - always executes
}
The catch block is optional, but if present, the finally block executes after the catch block −
try {
// risky code
} finally {
// cleanup code - no catch block needed
}
How Finally Works
Example with Exception Handling
using System;
class DivNumbers {
int result;
DivNumbers() {
result = 0;
}
public void division(int num1, int num2) {
try {
result = num1 / num2;
Console.WriteLine("Division successful");
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e.Message);
} finally {
Console.WriteLine("Result: {0}", result);
Console.WriteLine("Finally block executed");
}
}
static void Main(string[] args) {
DivNumbers d = new DivNumbers();
Console.WriteLine("--- Test 1: Division by zero ---");
d.division(25, 0);
Console.WriteLine("
--- Test 2: Normal division ---");
d.division(25, 5);
}
}
The output of the above code is −
--- Test 1: Division by zero --- Exception caught: Attempted to divide by zero. Result: 0 Finally block executed --- Test 2: Normal division --- Division successful Result: 5 Finally block executed
Using Finally for Resource Cleanup
using System;
using System.IO;
class FileHandler {
public static void ProcessFile(string fileName) {
StreamReader reader = null;
try {
reader = new StreamReader(fileName);
Console.WriteLine("File opened successfully");
string content = reader.ReadToEnd();
Console.WriteLine("Content length: " + content.Length);
} catch (FileNotFoundException) {
Console.WriteLine("File not found: " + fileName);
} catch (Exception ex) {
Console.WriteLine("An error occurred: " + ex.Message);
} finally {
if (reader != null) {
reader.Close();
Console.WriteLine("File closed in finally block");
} else {
Console.WriteLine("No file to close");
}
}
}
static void Main(string[] args) {
ProcessFile("nonexistent.txt");
}
}
The output of the above code is −
File not found: nonexistent.txt No file to close
Key Rules
-
The
finallyblock always executes, regardless of whether an exception occurs. -
It executes even if there is a
returnstatement in thetryorcatchblock. -
The
finallyblock is optional ? you can havetry-catchwithoutfinally. -
Use
finallyfor cleanup operations like closing files, database connections, or releasing memory.
Conclusion
The finally statement in C# ensures that critical cleanup code always executes, whether an exception occurs or not. It is essential for proper resource management and maintaining application stability by guaranteeing that cleanup operations like closing files or database connections are performed.
