C# Exception Handling — Complete Beginner Guide
Learning Objectives
- Catch and handle runtime errors with try and catch
- Run cleanup logic in finally
- Throw meaningful exceptions
- Filter catches with when clauses
- Design failure paths that stay readable
What Is an Exception
An exception is an object that signals a runtime problem. When code throws, normal flow stops until a matching catch handles it. If nothing handles the error, the program typically terminates with a message.
try
{
int[] nums = { 1, 2, 3 };
Console.WriteLine(nums[5]);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Bad index: " + ex.Message);
}
The catch block runs only when the thrown type matches the listed type.
try, catch, and finally
try wraps risky code. catch responds to failures. finally always runs afterward for cleanup.
try
{
Console.WriteLine("Start");
int result = 10 / 0;
Console.WriteLine(result);
}
catch (DivideByZeroException)
{
Console.WriteLine("Cannot divide by zero");
}
finally
{
Console.WriteLine("Cleanup always runs");
}
finally is ideal for closing resources or printing end markers regardless of success.
Catching Multiple Types
Order matters. Catch more specific types before general ones.
try
{
string raw = "abc";
int n = int.Parse(raw);
Console.WriteLine(n);
}
catch (FormatException ex)
{
Console.WriteLine("Format issue: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Unexpected: " + ex.Message);
}
Catching bare Exception can hide bugs. Prefer catching the specific exceptions you understand.
when Filters
A when clause adds a condition to a catch. The handler runs only if both the type and the condition match.
try
{
int[] data = { 10 };
int index = 7;
Console.WriteLine(data[index]);
}
catch (IndexOutOfRangeException when (index > 100))
{
Console.WriteLine("Index far out of range");
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Index was invalid");
}
Filters let you route rare cases separately without nested logic.
Practical filter with context
void ReadValue(int id)
{
try
{
if (id <= 0)
{
throw new ArgumentOutOfRangeException(nameof(id), "Id must be positive");
}
Console.WriteLine("Reading " + id);
}
catch (ArgumentOutOfRangeException when (id == 0))
{
Console.WriteLine("Zero id special case");
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}
}
ReadValue(0);
ReadValue(-2);
ReadValue(4);
Throwing Exceptions
Use throw to signal invalid states or failed preconditions.
void SetAge(int age)
{
if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}
Console.WriteLine("Age set to " + age);
}
try
{
SetAge(-1);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
Exception Properties
| Property | Purpose |
|---|---|
| Message | Human readable description |
| StackTrace | Path of calls that led to the throw |
| InnerException | Wrapped lower level error |
| Source | Assembly or component that raised it |
Logging Message together with StackTrace during development speeds up diagnosis.
Custom Exceptions
class OutOfStockException : Exception
{
public OutOfStockException(string sku)
: base("Out of stock: " + sku)
{
}
}
try
{
throw new OutOfStockException("SKU-9");
}
catch (OutOfStockException ex)
{
Console.WriteLine(ex.Message);
}
Custom types make domain failures explicit in catch blocks.
Design Guidelines
- Handle exceptions where you can actually recover
- Prefer early validation to prevent exceptions when practical
- Do not swallow errors with empty catch blocks
- Use finally or using for deterministic cleanup
- Let unexpected failures bubble to a global handler in apps
Common Mistakes
Catch and ignore
Empty catches hide problems and make debugging painful. At least log the failure.
Only catching Exception
You may miss the precise type information needed for correct recovery.
Throwing strings
throw with a plain string loses type structure. Throw real exception types instead.
Key Takeaways
💡
- try contains risky work; catch handles matching failures
- finally runs whether the try succeeded or not
- when filters add conditions to catch selection
- throw signals errors with real exception types and clear messages
- Catch specifically and never silently swallow exceptions
Practice Questions
- In what order do try, catch, and finally execute during a failure?
- What does a when filter change about catch behavior?
- Why is catching only Exception often a bad idea?
- Which exception type does dividing an int by zero raise in C#?
- Write a method that validates a positive quantity and throws ArgumentException when the value is zero or less, then handle it in try and catch.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions