Exceptions & resource management
Exceptions represent exceptional failure paths. try contains code that may fail, catch handles selected exceptions and finally runs regardless of success or failure.
Handling exceptions
Catch the most specific exception you can actually handle. A broad catch (Exception) that simply ignores the error hides failures. Inside a catch, throw; rethrows while preserving the original stack trace; throw ex; loses useful stack information.
try
{
var text = File.ReadAllText("settings.txt");
Console.WriteLine(text);
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"Missing file: {ex.FileName}");
}IDisposable and using
The garbage collector manages managed memory, but files, streams and some OS/native resources need deterministic cleanup. Types that own such resources commonly implement IDisposable; using ensures Dispose() is called even if an exception occurs.
using var reader = File.OpenText("settings.txt");
string content = reader.ReadToEnd();Key points
- Exceptions are for exceptional paths, not routine branching.
- Prefer specific catches; do not silently swallow failures.
- GC manages memory;
Dispose/usinghandles deterministic release of disposable resources.