6. Exception Handling
1. What are Exceptions?
Error vs Exception
int x = "hello"; // Compile-time errorint[] numbers = { 1, 2, 3 };
int x = numbers[10]; // Runtime exception (IndexOutOfRangeException)Exception Hierarchy
System.Object
│
└─ System.Exception (base for all exceptions)
│
├─ System.SystemException (runtime errors)
│ ├─ NullReferenceException
│ ├─ IndexOutOfRangeException
│ ├─ InvalidOperationException
│ ├─ ArgumentException
│ │ ├─ ArgumentNullException
│ │ └─ ArgumentOutOfRangeException
│ ├─ DivideByZeroException
│ ├─ OverflowException
│ ├─ StackOverflowException
│ ├─ OutOfMemoryException
│ ├─ FormatException
│ └─ InvalidCastException
│
├─ System.IO.IOException
│ ├─ FileNotFoundException
│ ├─ DirectoryNotFoundException
│ └─ EndOfStreamException
│
└─ Custom exceptions (derive from Exception)
└─ MyCustomException2. Common Exception Types
Exception
When Thrown
Example
System-Level vs Application-Level Exceptions
3. Try-Catch-Finally
Basic Structure
Try-Catch-Finally Flow
Catching Specific Exceptions
Exception Filters (C# 6.0+)
4. Multiple Catch Clauses
Order Matters! (Most Specific First)
Multiple Exceptions in One Catch (C# 6.0+)
5. Nesting Try-Catch Blocks
6. Throwing Exceptions
throw Keyword
throw vs throw ex (CRITICAL!)
Throw Expressions (C# 7.0+)
7. Custom Exceptions
Creating Custom Exceptions
Best Practices for Custom Exceptions
8. Exception Properties
Walking the Exception Chain
9. Best Practices
When to Catch Exceptions
Specific vs General Exceptions
Don't Use Exceptions for Control Flow
Log Exceptions
Fail Fast Principle
10. Resource Management
IDisposable Pattern
IDisposable Interface
Basic Implementation
Full Dispose Pattern (with Finalizer)
using Statement (C# 1.0)
Multiple Resources
using Declaration (C# 8.0+)
IAsyncDisposable (C# 8.0+)
using Statement Evolution
11. Exception Handling with Async
try-catch in Async Methods
AggregateException
Handling Task Exceptions
Common Patterns
Pattern 1: Try-Parse
Pattern 2: Retry Logic
Pattern 3: Exception Translation
Pattern 4: Safe Disposal
Anti-Patterns (What NOT to Do)
❌ Empty Catch Block
❌ Catching Exception Without Re-throwing
❌ throw ex Instead of throw
❌ Exception for Control Flow
❌ Catching and Doing Nothing
Decision Tree: Should I Catch This Exception?
Quick Reference Summary
Exception Hierarchy
Try-Catch-Finally
Throwing
Resource Management
Best Practices
Last updated