🎉 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++ FundamentalsC++ Exception Handling — try, catch, custom Exceptions🟢 Free Lesson

C++ Exception Handling — Complete Beginner Guide

Learning Objectives

  • Throw and catch exceptions correctly
  • Understand stack unwinding during failure
  • Design a simple custom exception type
  • Decide when exceptions fit your error style

What Exceptions Are For

Exceptions represent exceptional conditions that disrupt normal flow: failed input conversion, out of range access, or missing files. Instead of checking every call for a status flag, you throw an exception and handle it where recovery makes sense.

try, throw, and catch

The try block wraps code that might fail. throw raises an error object. catch handles it.

#include <iostream>
#include <stdexcept>

int main() {
    try {
        int value = 0;
        if (value == 0) {
            throw std::runtime_error("value must not be zero");
        }
        std::cout << value << std::endl;
    } catch (const std::runtime_error& err) {
        std::cout << "error: " << err.what() << std::endl;
    }
    return 0;
}
KeywordRole
tryMarks guarded code
throwRaises an exception object
catchHandles a matching type
whatReads the explanatory message

How Control Moves

When throw executes, normal execution stops. The runtime searches for a matching catch by unwinding the call stack. Destructors of local objects run during unwinding, which is RAII working in your favor. If no handler exists, std::terminate typically ends the program.

void stepThree() {
    throw std::logic_error("bad state");
}

void stepTwo() {
    stepThree(); // exception propagates here
}

void stepOne() {
    stepTwo(); // and then here toward a handler
}

int main() {
    try {
        stepOne();
    } catch (const std::exception& e) {
        std::cout << e.what() << std::endl;
    }
    return 0;
}

Catching By Const Reference

Catch exception objects by const reference so the full derived message is preserved without slicing and without unnecessary copies.

catch (const std::exception& e) {
    // handle standard failures
}

You may catch more specific types first, then a broader handler later.

Standard Exception Types

TypeTypical Use
invalid_argumentBad input values
out_of_rangePosition or index problems
runtime_errorFailures detected during run
logic_errorBroken program logic assumptions
bad_allocHeap allocation failure

These types live with the standard library and carry messages through what.

Custom Exception Classes

For domain errors, define your own type that inherits from a standard exception.

#include <stdexcept>
#include <string>

class ScoreError : public std::out_of_range {
public:
    explicit ScoreError(const std::string& msg)
        : std::out_of_range(msg) {}
};

void normalize(int& score) {
    if (score < 0 || score > 100) {
        throw ScoreError("score must be between 0 and 100");
    }
}

Callers can catch ScoreError specifically or the standard base for a generic path.

Multiple Handlers

try {
    // risky work
} catch (const ScoreError& e) {
    // domain fix
} catch (const std::exception& e) {
    // general fallback
} catch (...) {
    // absolute last resort for unknown types
}

Order matters: more specific handlers should appear before broader ones when inheritance is involved.

Exceptions Versus Error Codes

ApproachProsCons
Return codesExplicit, no hidden flowEasy to ignore
ExceptionsSkips deep error plumbingLess obvious control path

Many modern C plus plus libraries throw on failure. Learn both styles so you can read older codebases that prefer codes.

Exception Safety Habits

  • Do not throw from destructors during normal cleanup
  • Keep throwing constructors rare unless the object can never be valid
  • Prefer RAII so unwinding does not leak
  • Provide useful messages that state what failed and why
  • Avoid exception objects that contain heavy unneeded state

A Practical Example

#include <iostream>
#include <stdexcept>
#include <string>

double divide(double a, double b) {
    if (b == 0.0) {
        throw std::invalid_argument("divisor cannot be zero");
    }
    return a / b;
}

int main() {
    try {
        std::cout << divide(10.0, 2.0) << std::endl;
        std::cout << divide(1.0, 0.0) << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cout << "caught: " << e.what() << std::endl;
    }
    return 0;
}

The first call succeeds. The second triggers the handler instead of producing undefined math results.

Common Mistakes

MistakeFix
Throwing string literals onlyThrow typed exception objects
Catching by valueCatch by const reference
Swallowing errors silentlyLog or rethrow meaningfully
Throwing across thread boundaries casuallyLearn threading rules later
Ignoring that what can be emptyProvide a message at throw time

Key Takeaways

💡

  • throw raises; catch handles; try marks risky regions
  • Stack unwinding runs destructors while searching for handlers
  • Catch by const reference to keep derived messages intact
  • Custom exceptions clarify domain failures for callers
  • Combine exceptions with RAII for safe cleanup paths

Practice Questions

  1. Write a function that throws out_of_range when a vector index is invalid.
  2. Why should catch clauses usually use const references?
  3. What happens if no matching catch exists for a thrown exception?

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