Multiple catch Blocks in C++
Handle several exception types in C++ with multiple catch blocks: invalid_argument, out_of_range, runtime_error, and catch(...), and why order matters.
1#include <iostream>2#include <stdexcept>3using namespace std;45void processNumber(int num) {6 if (num < 0) {7 throw invalid_argument("Number cannot be negative");8 }9 if (num > 100) {10 throw out_of_range("Number exceeds maximum value");11 }12 if (num == 0) {13 throw runtime_error("Number cannot be zero");14 }1516 cout << "Processing number: " << num << endl;17}1819int main() {20 int numbers[] = {5, -3, 150, 0, 50};2122 for (int num : numbers) {23 try {24 processNumber(num);25 } catch (const invalid_argument& e) {26 cout << "Invalid argument: " << e.what() << endl;27 } catch (const out_of_range& e) {28 cout << "Out of range: " << e.what() << endl;29 } catch (const runtime_error& e) {30 cout << "Runtime error: " << e.what() << endl;31 } catch (...) {32 cout << "Unknown error occurred" << endl;33 }34 }3536 return 0;37}
Sample Output
Invalid argument: Number cannot be negative
-3 caught by the first handler.
Processing number: 50
No exception; the loop kept going.
In this one
- How C++ picks the first matching catch block
- Why specific catch types go before general ones
- What catch(...) does
- Why the try sits inside the loop
How it works
- 1
Loop over 5, -3, 150, 0, 50.
- 2
Call processNumber inside try.
- 3
-3 → invalid_argument; 150 → out_of_range; 0 → runtime_error.
- 4
The matching catch prints a label and what().
- 5
5 and 50 print normally.
Edge cases
General handler first
Move catch (const exception& e) to the top.
It matches every one of these exceptions, so the specific handlers never run. Many compilers warn about the unreachable handlers.
Throwing a non-exception type
Make processNumber throw 42 for 7.
None of the typed handlers match an int, so catch (...) prints "Unknown error occurred".
try outside the loop
Wrap the whole for loop in one try.
The loop stops at -3, so 150, 0, and 50 are never processed.
What's going on
One try block can have several catch blocks, one per kind of error. When an exception is thrown, C++ checks the catch blocks in order and runs the first one whose type matches. This program throws a different standard exception for each kind of bad number.
processNumber throws invalid_argument for a negative number, out_of_range for anything over 100, and runtime_error for zero. Valid numbers are printed. All three are classes from <stdexcept>, built with a message that what() returns later.
main loops over {5, -3, 150, 0, 50}, and the try-catch is inside the loop. That placement matters: each number gets its own try, so an error on -3 is handled and the loop moves on to 150. Had the loop been inside the try, the first exception would have ended the whole loop.
5 and 50 are printed normally. -3 matches the invalid_argument handler, 150 the out_of_range handler, and 0 the runtime_error handler. Each handler prints its own label and e.what().
The last handler, catch (...), catches anything at all, even an int or a string literal. It goes last because it would otherwise grab everything.
Order matters with class hierarchies. invalid_argument and out_of_range both derive from logic_error, which derives from exception. If you put catch (const exception& e) first, it would catch all three and the specific handlers would never run. Put the most specific types first and the most general last.
Catching by const& avoids copying the exception and keeps its real type, so what() returns the right message.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <stdexcept> is there because it provides standard exception classes. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Multiple Catch Blocks
Multiple Catch Concept:
Catch Order:
Standard Exception Types
Common Types:
What happens here:
Throwing Different Exceptions
Throwing Specific Types:
if (num < 0) {
throw invalid_argument("Number cannot be negative");
}
if (num > 100) {
throw out_of_range("Number exceeds maximum value");
}
What happens here:
Catching Specific Exceptions
Multiple Catch Blocks:
catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << endl;
} catch (const out_of_range& e) {
cout << "Out of range: " << e.what() << endl;
} catch (const runtime_error& e) {
cout << "Runtime error: " << e.what() << endl;
}
What happens here:
Catch-All Block
Using catch(...):
catch (...) {
cout << "Unknown error occurred" << endl;
}
What happens here:
When to Use Multiple Catch Blocks
Good fits:
Example Scenarios:
Important Considerations
Catch Order:
Exception Hierarchy:
Error Messages:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
If catch (const exception& e) is the first handler, what prints for -3?
Pick an answer to check it.
Question 2
Why does 150 trigger out_of_range and not invalid_argument?
Pick an answer to check it.
Questions people ask
Can one catch handle two types?
Not directly. Catch a common base class, such as logic_error, or repeat the handler.
Why catch by reference?
Catching by value copies the exception and slices off the derived part, so a base-class catch would lose the real type.
Can I get the message inside catch (...)?
No. You can rethrow with throw; to let another handler deal with it.