Error / Exception Handling in C#
Handle errors with try/catch/finally, catch filters (when), throw expressions, custom exceptions, AggregateException, and global exception handlers.
Introduction to Exceptions
1. What is an Exception?
An exception is a runtime error that disrupts the normal flow of execution.
Types of Exceptions
1. System Exceptions (Runtime Errors)
Built-in exceptions thrown by the .NET runtime for programming mistakes.
2. Application Exceptions (Domain Errors)
`ApplicationException` is the base for user-defined exceptions.
3. Common Exception Types
Quick reference of the most frequently encountered exceptions.
try / catch
1. Basic try-catch
Wrap risky code in `try` and handle the error in `catch`.
2. The Exception Object
The caught exception exposes `Message`, `StackTrace`, and `InnerException`.
3. Multi-catch
Use multiple `catch` blocks to handle different exception types differently.
finally Block
1. finally Execution
`finally` runs whether the try block succeeded or threw.
Throwing Exceptions
1. throw new Exception
Use `throw` to raise an exception from your own code.
2. Rethrow — throw vs throw ex
Use bare `throw` to rethrow without losing the original stack trace.
Custom Exception Classes
1. Extending Exception
Inherit from `Exception` to create meaningful domain exceptions.
Error Propagation
1. Exception Bubbling
An unhandled exception travels up through each caller until caught.
using / IDisposable
1. using Statement (Automatic Resource Closing)
`using` calls `Dispose()` automatically — even if an exception is thrown.
2. Custom IDisposable
Implement `IDisposable` to make your own class work with `using`.
Stack Trace & Call Stack
1. What is a Stack Trace?
A stack trace shows the chain of method calls at the moment an exception was thrown.
2. Getting Stack Trace Without an Exception
`Environment.StackTrace` gives the current call stack at any point.
Exception Filters
1. catch (Exception ex) when (...)
`when` adds a condition to a catch block — the exception is only caught if the condition is true.