What is the purpose of finally block in C#?
an extensive exception handling mechanism using try..catch blocks. While
executing a block of code inside try block, if there are any error occurrences
then the appropriate catch block will be triggered based on the order
in which it appears.
When the exception occurs, the program terminates from inside catch block. But there might be some critical section of code which has to be executed even if an exception occurs.
For example, your code might use unmanaged resources. If there is any exception occurrence and your program is going to terminate then before terminating it is essential to release all unmanaged resources. Where do you do it? You can write such critical section of code inside finally block. Code inside finally block will be executed at all times irrespective of exceptions. This is demonstrated using the example shown below:
In the above example, you read the contents of file sample.txt inside try block. If there are any error occurrences like OutofMemoryException then catch block will execute. In normal cases, the program will terminate. Since you have included finally block, the code inside finally block will execute even if an exception is caught and therefore the sampleReader will get closed irrespective of exception occurrences.