In this article we’ll talk about Finally Block in C#. What and where we can use this and about its PROS and CONS too. If you haven’t checked my previous article on “Multiple Catch blocks in C#” then please check that first for better understanding.
What we’ll cover in this article:
Important points of Finally Block in C#
- Finally block always execute regardless of any exception.
- Multiple finally blocks in the same try block are not allowed.
- Finally block is always executed after the try and catch blocks, but before control transfers back to its origin calling method.
- It does not support return, continue, break statements because it does not allow controls to leave the finally block until it executes completely.
- You can also use finally block only with a try block means without a catch block but in this situation, no exceptions are handled.
What is finally block in C#?
‘Finally’ is a reserved keyword in C#. It is a block of statements that are always executed, regardless of any exceptions that occur in an application. It is used optionally with the “try/catch/finally” or “try/finally” block and guarantees the execution of any code that must be executed before exiting the “try” block, regardless of the success or failure of the application’s execution.
As you can see below, in two ways we can write the finally block in C#. They are as follows:
- Try, Catch, and Finally: In this case, the exception will be handled by the CATCH block, no abnormal termination occurs in this case and “finally” block code gets executed at any cost.
- Try and Finally: In this case, abnormal termination will occur because of missing CATCH block but even after that finally blocks will get executed.
var connection = new SqlConnection();
connection.Open()
try
{
// execute a code
}
catch(Exception ex)
{
// handle an exception
}
finally
{
// do all required cleanup
// if the code executes with or without an exception, we'll close connection here
connection.Close();
}
What, if finally re- throw error, let’s check below?
Whenever an exception occurs in the try block, control passes from the line that caused the exception to the relevant catch block (Check multiple CATCH block exception handler) and then to the finally block. Also, when an exception is re-thrown in a catch block, control transfers to the finally block. Next if exceptions again occur in finally then it will be bubbled up to its parent method Catch block. Thus, next code after the line (with in try) where the exception occurred will be skipped.
If your program contains “break”, “goto”, “continue” or “return” statement in Try block or due to any exception when control exits from try block, every time finally block is executed.
Additionally, exceptions should not be thrown explicitly in a finally block. If an exception occurs during the execution of a finally block, any code after the point where the exception is thrown will not execute, and current exception will propagate to the outer try block or to parent method try block.
Care should be taken not to explicitly transfer execution into or out of a finally block as this is not a valid transfer.
How to use finally in our C# program?
The execution of Finally block is to release resources, such as database connections, IO operations which are usually available in limited quantities. Using this disposal of resources occurs earlier than the garbage collector’s finalization operation, thereby it is optimizing memory usages.
Conclusion: We should use “Finally” block when we work with IO operation or network connections etc. so that memory can be released.
Is this really required to use finally in C#?
Yes, one should use it to optimize the memory before Garbage Collector (GC) take care of it. Especially in case of IO streams and network connections.
What are Pros & Cons?
PROS: Considering the memory optimization one must use this in his/her daily development practices.
CONS: We know that finally block will execute once in the lifetime of that program, so developer should write code for object dispose or for memory optimization only. Any extra code can cause performance issues.
Can we skip finally block in C#?
Finally block of code always executes, irrespective of any Exception in program. You can never skip the execution of the final block.
In this article we tried to explain Finally Block in C# with Examples. I hope you enjoyed reading this article. For more information you can check out Microsoft learn.
For more information you can visit our C# Section for more such articles.