CHAPTER 21
Beginner
Exception Handling in C++
Updated: May 17, 2026
5 min read
# CHAPTER 21
Exception Handling
1. Introduction
Errors happen. A user types a letter instead of a number, a file goes missing, or a division by zero occurs. If you don't handle these errors, the program crashes abruptly (Segmentation Fault or Floating Point Exception). Exception Handling allows you to gracefully catch these errors, report them, and keep the program running.2. Learning Objectives
By the end of this chapter, you will be able to:-
Understand the
try,throw, andcatchkeywords.
- Catch multiple types of exceptions.
-
Understand the "catch-all" handler
catch(...).
- Create Custom Exception classes.
- Ensure Exception Safety.
3. The Big Three: Try, Throw, Catch
-
try: A block of code that you suspect might cause an error.
-
throw: Used to manually trigger an error when a problem is detected.
-
catch: A block of code that handles the error if one is thrown.
cpp
*Output:*
text
4. Catching Multiple Exceptions
Atry block can have multiple catch blocks depending on what type of data is thrown (an int, a string, an object, etc.).
cpp
5. The Catch-All Handler
If you want to catch *any* exception that might be thrown, regardless of its data type, usecatch(...).
cpp
6. Standard Exceptions (std::exception)
C++ provides a standard library of exceptions <stdexcept>. Instead of throwing raw strings or ints, it is best practice to throw standard objects like std::invalidargument or std::outof_range.
cpp
7. Custom Exceptions
You can create your own exception classes by inheriting fromstd::exception.
cpp
8. Mini Project: Safe Calculator
cpp
9. Memory-Level Explanation
When an exception is thrown, the C++ runtime performs Stack Unwinding. It looks at the current Stack Frame. If there is nocatch block, it destroys that frame (cleaning up local variables) and moves down to the caller's frame. It continues unwinding the stack until it finds a catch block. If it reaches main() and finds no catch block, the OS forcefully terminates the program.
10. Common Mistakes
-
Memory Leaks during Stack Unwinding: If you allocate memory with
new, and an exception is thrown *before* you calldelete, that memory is leaked. (This is why Smart Pointers are used in Modern C++!).
-
Catching by Value instead of Reference:
catch(exception e)creates a copy of the exception object, which is slow and can cause "object slicing". Always usecatch(const exception& e).
11. Exercises
-
1.
Write a program that asks for a user's age. If the age is negative, throw an
invalidargumentexception.
-
2.
Create an array of size 5. Ask the user for an index to access. If the index is > 4, throw an
outof_rangeexception.
12. MCQ Quiz with Answers
Question 1
Which keyword is used to trigger an exception?
Question 2
Which block contains the code that handles the error?
Question 3
How do you catch all types of exceptions?
Question 4
What is the base class for all standard C++ exceptions?
Question 5
Which method of std::exception returns the error message string?
Question 6
What happens during Stack Unwinding?
catch (const exception& e))
Answer: b) By reference
Question 8
What happens if an exception is thrown but never caught?
throw 404;)
Question 10
Why is try-catch preferred over simple if statements for error handling?
13. Interview Questions
- Q: Explain Stack Unwinding in the context of C++ Exceptions.
-
Q: Why should you catch exceptions by
constreference?
-
Q: Explain the
noexceptspecifier in Modern C++. (Answer: It tells the compiler that a function will *never* throw an exception, allowing the compiler to optimize the code heavily).
14. Summary
Exception handling (try, throw, catch) provides a structured way to handle runtime errors without crashing the program. By utilizing std::exception and catching by reference, you can build robust, error-tolerant software.