Roadmap › C# Language — Basics to Advanced › Module: Errors, Resources and Memory
Lessons in this course (38)

27. Exception handling

Basic★ Must knowLesson 27 of 38
csharp
try
{
    var text = File.ReadAllText(path);
}
catch (FileNotFoundException ex) when (path.EndsWith(".cfg"))   // exception filter
{
    logger.LogWarning(ex, "Config missing");
}
catch (IOException ex)
{
    throw new ConfigException("Could not read config", ex);      // wrap, keep inner exception
}
finally
{
    // always runs (cleanup)
}
  • throw; rethrows and keeps the original stack trace; throw ex; resets it — avoid.
  • Catch specific exceptions first, general ones last.
  • Don't use exceptions for normal control flow; use TryParse-style APIs.
  • Custom exception: derive from Exception, provide the standard constructors (next lesson).