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;
}
| Keyword | Role |
|---|---|
| try | Marks guarded code |
| throw | Raises an exception object |
| catch | Handles a matching type |
| what | Reads 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
| Type | Typical Use |
|---|---|
| invalid_argument | Bad input values |
| out_of_range | Position or index problems |
| runtime_error | Failures detected during run |
| logic_error | Broken program logic assumptions |
| bad_alloc | Heap 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
| Approach | Pros | Cons |
|---|---|---|
| Return codes | Explicit, no hidden flow | Easy to ignore |
| Exceptions | Skips deep error plumbing | Less 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
| Mistake | Fix |
|---|---|
| Throwing string literals only | Throw typed exception objects |
| Catching by value | Catch by const reference |
| Swallowing errors silently | Log or rethrow meaningfully |
| Throwing across thread boundaries casually | Learn threading rules later |
| Ignoring that what can be empty | Provide 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
- Write a function that throws out_of_range when a vector index is invalid.
- Why should catch clauses usually use const references?
- 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
- 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