Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediateException Handling ProgramsExample 2 of 5
multiple-catch-blocks.cpp
1#include <iostream>
2#include <stdexcept>
3using namespace std;
4
5void 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 }
15
16 cout << "Processing number: " << num << endl;
17}
18
19int main() {
20 int numbers[] = {5, -3, 150, 0, 50};
21
22 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 }
35
36 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. 1

    Loop over 5, -3, 150, 0, 50.

  2. 2

    Call processNumber inside try.

  3. 3

    -3 → invalid_argument; 150 → out_of_range; 0 → runtime_error.

  4. 4

    The matching catch prints a label and what().

  5. 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:

Different catch blocks for different types
Checked in order (top to bottom)
First matching catch executes
More specific before general

Catch Order:

Specific exceptions first
General exceptions last
catch(...) as catch-all
Order matters!

Standard Exception Types

Common Types:

invalid_argument: invalid parameter
out_of_range: value out of range
runtime_error: runtime error
logic_error: logic error

What happens here:

Each type for specific errors
Provides what() method
Inherits from exception
Standard error handling

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:

Throw specific exception types
Each type for specific error
Provides error message
Caught by matching catch

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:

Each catch handles specific type
Checked in order
First match executes
Others skipped

Catch-All Block

Using catch(...):

catch (...) {

cout << "Unknown error occurred" << endl;

}

What happens here:

Catches any exception type
Must be last catch block
No exception value access
Safety net for unexpected errors

When to Use Multiple Catch Blocks

Good fits:

Different error types
Type-specific handling
Precise error messages
Different recovery strategies
Comprehensive error handling

Example Scenarios:

Input validation (multiple checks)
File operations (different errors)
Network operations (various failures)
Database operations (different errors)

Important Considerations

Catch Order:

More specific first
General last
catch(...) always last
Wrong order = wrong catch

Exception Hierarchy:

Standard exceptions inherit from exception
Can catch base class
More general catch catches derived
Understand inheritance

Error Messages:

Use what() method
Provides error description
Help with debugging
Inform users

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.