What is the purpose of finally block in C#?

C# provides 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:

public class sampleClass {
public static void Main() {
StreamReader sampleReader = new StreamReader(“sample.txt”);
try {
sampleReader = new StreamReader(“sample.txt”);
string sampleStr;
while ((sampleStr = sampleReader.ReadLine()) != null) {
Console.WriteLine(sampleStr);
}
}
catch(Exception exp) {
Console.WriteLine(“Exception Occurred:”+exp);
}
finally {
if (sampleReader != null) {
sampleReader.Close();
}
}
}
}

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.

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.