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