Finally Block in C#
In C#, an exception can result in an error that terminates the active method. This approach might have started a network or file that needs to be closed. Thus, C# offers a specific keyword called the finally keyword which is used to address these kinds of issues. In C#, it is a reserved keyword.
The finally block runs in every condition by which the try/catch block exits the execution. It always runs, regardless of how the try block ends normally or as a result of an exception. The release of system resources is the primary goal of the finally block. After the try/catch block comes the finally block.
The establishment of a block by the keyword finally ensures that all the statements within it are executed without fail, regardless of whether an exception has happened or not. This means that the statement includes in the finally block is guaranteed to be executed regardless of whether an exception is thrown in the try block or not and regardless of whether the exception is handled by the catch block or not.
Syntax of finally block in C#
try {
// statements
}
catch {
// statements
}
finally
{
// statements
}
In this, firstly try and catch block executed, and after the execution of the exception block, finally block is executed.
Points to remember while executing Finally Block
- Multiple finally blocks are not permitted in a single C# program.
- Every try block contains a finally block
- The catch block is optional while executing the finally block.
- There is no return, continue, or break statements in the finally block as it does not allow controls to leave the finally block.
- Every try block contains more than one or no catch blocks but it must contain at most one finally block.
Why Should We Use Finally Block in C#?
We have to work with external resources for our programs in numerous applications. Files, network connections, graphic elements, pipes, and streams to or from various hardware devices (such as printers, card readers, and others) are examples of external resources. When dealing with such external resources, it is crucial to release them as soon as possible after they are no longer required. For instance, we must immediately close the file after reading its contents when we open a file to read its contents (let's say to load a JPG image). If we leave the file open, the operating system will block specific operations on the file from being performed by other users and apps.
The finally block is used to free an external resource or for cleanup. The finally block ensures that cleanup procedures won’t be mistakenly skipped as a result of an unknown exception or the execution of return, continue, or break.
Let’s understand the concept of the finally block with a few examples in C#.
Example 1: A simple program to demonstrate the finally block.
CODE
using System;
class Project {
static void A()
{
try {
Console.WriteLine("Inside A");
throw new Exception("Throwing Exception");
}
finally
{
Console.WriteLine("A's finally");
}
}
static void B()
{
try {
Console.WriteLine("Inside B");
return;
}
finally
{
Console.WriteLine("B's finally");
}
}
public static void Main(String[] args)
{
try {
A();
}
catch (Exception) {
Console.WriteLine("Exception Caught");
}
B();
}
}
OUTPUT
![Finally Block in C#](https://static.tutorialandexample.com/csharp/finally-block-in-csharp1.png)
In this code, we have determined how the finally block is executed. A method named A is made which throws an exception and has the finally block. It is called under the try-catch block. There is another method named B which also has the finally block and is called outside the try-catch block.
Example 2: Program to demonstrate the use of finally block with the handled exception in C#.
CODE
using System;
public class Temp {
static public void Main()
{
int num = 14;
int div = 0;
try {
int out = num / div;
}
catch ( DividingByZero ) {
Console.WriteLine("Not possible to divide by zero!");
}
finally {
Console.WriteLine("Finally Block!");
}
}
}
OUTPUT
![Finally Block in C#](https://static.tutorialandexample.com/csharp/finally-block-in-csharp2.png)
In this program, an exception DividingByZero is made inside the try block that is captured by the catch block. Then, the finally block is executed when the try-catch block leaves the execution which releases the system resources that are being used by the try-catch block before it finished its execution.
Example 3: Program to understand the use of the finally block without the catch block in C#.
CODE
using System;
namespace example
{
class resource
{
static void S_Method()
{
try
{
Console.WriteLine("Inside SomeMethod");
int num1 = 10, num2 = 0;
int result = num1 / num2;
Console.WriteLine($"Result: {result}");
}
finally
{
Console.WriteLine("SomeMethod finally Block");
}
}
static void Main(string[] args)
{
try
{
S_Method();
}
catch (Exception)
{
Console.WriteLine("Exception Caught");
}
Console.ReadKey();
}
}
}
OUTPUT
![Finally Block in C#](https://static.tutorialandexample.com/csharp/finally-block-in-csharp3.png)
In this code, no catch block is there. The finally block is used only with the try block
Benefits of Using Finally Block
- The finally code is executed regardless of the execution, which means whether the execution is handled on not but the finally block will be executed.
- The basic use of the finally block is to release the expensive resources of the try block.
- It ensures the execution of the code is performed regardless of the exception thrown.