finally for cleanup
Context: The finally block is used to execute code regardless of whether an exception was thrown. It is ideal for releasing resources (file handles, database connections, locks). Unlike catch, finally does not handle the exception; it runs after the try and any matching catch, and then the exception continues to propagate.
Usage Example
Section titled “Usage Example”using System;using System.IO;
class Program{ static void Main() { FileStream fs = null; try { fs = File.Open("test.txt", FileMode.OpenOrCreate); // Simulate an exception throw new InvalidOperationException("Something went wrong"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } finally { if (fs != null) { fs.Dispose(); Console.WriteLine("FileStream disposed."); } } }}Output console
Section titled “Output console”dotnet runError: Something went wrongFileStream disposed.Important notes
Section titled “Important notes”finallyruns even if there is areturnintryorcatch.- Do not throw exceptions in
finally; they will replace the original exception. - The
usingstatement provides a cleaner syntax for disposal.
Real-world usage example
Section titled “Real-world usage example”Lock release – Using Monitor.Enter and Monitor.Exit in finally ensures the lock is released even if the protected code throws.
See .NET docs on finally.