try catch finally
Context: The try-catch-finally block is the fundamental mechanism for handling exceptions in C#. Code that may throw an exception is placed in the try block. If an exception occurs, control transfers to the appropriate catch block. The finally block executes regardless of whether an exception was thrown, and is typically used for cleanup (closing files, releasing resources). The finally block is optional but recommended for deterministic cleanup.
Usage Example
Section titled “Usage Example”using System;using System.IO;
class Program{ static void Main() { StreamReader reader = null; try { reader = new StreamReader("nonexistent.txt"); string content = reader.ReadToEnd(); Console.WriteLine(content); } catch (FileNotFoundException ex) { Console.WriteLine($"File not found: {ex.Message}"); } finally { reader?.Dispose(); Console.WriteLine("Cleanup completed."); } }}Output console
Section titled “Output console”dotnet runFile not found: Could not find file 'nonexistent.txt'.Cleanup completed.Important notes
Section titled “Important notes”- The
finallyblock always runs, even if no exception occurs or if areturnis insidetry. - You can have
try-finallywithoutcatch. - Never throw exceptions from
finallyblocks (they can hide original exceptions).
Real-world usage example
Section titled “Real-world usage example”Database connection handling – Using try-catch-finally to ensure SqlConnection is closed even if a query fails.
See .NET docs on try-catch-finally.