Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · C# · Chapter 08 / 10

Programming learning path

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/using handles deterministic release of disposable resources.

Source registry

2 chapter references
Exceptions and exception handling

Exception flow and handling rules

Microsoft Learn · Official documentation
Source ↗
Fundamentals of garbage collection

Managed heap, generations, collection and object lifetime

Microsoft Learn · Official documentation
Source ↗