C# - 'finally' block execution if code throws error
In C#, the finally
block always runs, whether or not there's an error in the try
block. The finally
block is typically used for cleaning up resources or executing code that must run regardless of whether an exception occurred or not.
Here's an example to illustrate this in C#:
using System;
class FinallyBlockExample
{
static void Main()
{
try
{
Console.WriteLine("Inside try block");
// Intentionally causing a division by zero exception
int divideByZero = 5 / 0;
}
catch (DivideByZeroException)
{
Console.WriteLine("Caught DivideByZeroException");
}
finally
{
Console.WriteLine("This is the finally block");
}
Console.WriteLine("Program execution continues here...");
}
}
Explanation
In this example:
- The
try
block contains code that will cause a DivideByZeroException
because it attempts to divide a number by zero.
- The
catch
block catches this specific type of exception and prints a message indicating that the exception was caught.
- The
finally
block is placed after the try
and catch
blocks. It will be executed regardless of whether the try
block was successful or an exception was caught in the catch
block.
The expected output of this program will be:
Inside try block
Caught DivideByZeroException
This is the finally block
Program execution continues here...
This demonstrates that the finally
block is executed even when an exception occurs in the try
block. After the finally
block executes, the normal flow of the program resumes.
Example 2.
In the below example you can see that finally
block get executed even exception is caught and thrown in catch
block:
Output:
To summarize, the purpose of the finally block is to guarantee that essential cleanup operations or resource freeing actions are executed, irrespective of whether an exception occurs and is handled or left unaddressed.
Note: The finally block will be executed in any case before the exception caught at the calling method.