🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C# Exception Handling — Complete Beginner Guide

C# FundamentalsException Handling🟢 Free Lesson

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

PropertyPurpose
MessageHuman readable description
StackTracePath of calls that led to the throw
InnerExceptionWrapped lower level error
SourceAssembly 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

  1. In what order do try, catch, and finally execute during a failure?
  2. What does a when filter change about catch behavior?
  3. Why is catching only Exception often a bad idea?
  4. Which exception type does dividing an int by zero raise in C#?
  5. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C# Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement