Exception Handling
Why Things Go Wrong
Programs crash. Files go missing. Users type "banana" when you asked for a number. The internet cuts out mid-download. A good developer doesn't just write code that works — they write code that fails gracefully.
In C#, when something goes wrong, the system throws an exception — it then walks up the call stack looking for a handler, like pulling the fire alarm. If nobody handles the alarm (catches the exception), the entire building evacuates (your program crashes). But if you set up a handler, you can deal with the problem calmly.
The three keywords:
try— "Here's some code that might fail."catch— "If it does fail, here's what to do instead."finally— "No matter what happened, always do this at the end."
Basic try/catch/finally
Common Exception Types
C# has many built-in exception types. Here are the ones you'll see most:
NullReferenceException— you tried to use something that'snull(the #1 bug in C#!)ArgumentException/ArgumentNullException— bad input passed to a methodInvalidOperationException— the object isn't in the right state for this operationIndexOutOfRangeException— array/list index too big or negativeFormatException— string couldn't be parsed to a numberFileNotFoundException— the file doesn't existDivideByZeroException— math with zero denominatorKeyNotFoundException— dictionary key doesn't exist
All exceptions inherit from System.Exception. When you catch Exception, you catch everything — but it's better to catch specific types so you know exactly what went wrong.
Throwing Exceptions & Custom Exceptions
Real-World Pattern: TryParse vs Parse
Quick check
Continue reading