C# exceptions: try, catch, finally and good habits
Short answer
Put risky code in try, handle errors you can recover from in catch, and release resources in finally, which runs whether or not an exception occurs. [S1][S2]
Good habits
- Catch only what you can handle; letting an app crash beats hiding a bug. [S2]
- Rethrow with
throw;to keep the original stack trace. [S2] - Design APIs so common failures do not need exceptions (for example
TryParse). [S2] - Prefer
usingfor disposable objects.
Claims
- id: C1 claim: Exceptions derive from System.Exception. source: S1 evidence: "Exceptions are types that all ultimately derive from System.Exception."
- id: C2 claim: finally runs regardless of exceptions. source: S1 evidence: "Code in a finally block is executed regardless of if an exception is thrown."
- id: C3 claim: A crashed app beats one with undefined behavior. source: S2 evidence: "a crashed app is more reliable and diagnosable than an app"
- id: C4 claim: Classes should be designed to avoid exceptions. source: S2 evidence: "Design classes so that exceptions can be avoided"
Sources
- [S1] Exceptions and Exception Handling - C#. Microsoft Learn. https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/exceptions/ . License: CC BY 4.0 (dotnet/docs). Accessed 2026-11-04.
- [S2] Best practices for exceptions - .NET. Microsoft Learn. https://learn.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions . License: CC BY 4.0 (dotnet/docs). Accessed 2026-11-04.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Microsoft Learn, Exceptions and Exception Handling - C#, CC BY 4.0 (dotnet/docs); Microsoft Learn, Best practices for exceptions - .NET, CC BY 4.0 (dotnet/docs).
Cite this
iinventedlight. 2026. "C# exceptions: try, catch, finally and good habits." iinventedlight Library, iil:note:ztgzkv9j, version of 2026-11-04. https://iinventedlight.com/library/notes/csharp-exceptions/. License: CC-BY-4.0.
@misc{iil_note_ztgzkv9j,
author = {{iinventedlight}},
title = {{C\# exceptions: try, catch, finally and good habits}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-04},
url = {https://iinventedlight.com/library/notes/csharp-exceptions/},
note = {Permanent ID iil:note:ztgzkv9j. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.
For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/csharp-exceptions.md.