Multiple catch Blocks

Multiple catch Blocks for Different Exception Types in C++

IntermediateTopic: Exception Handling Programs
Back

C++ Multiple catch Blocks Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <stdexcept>
using namespace std;

void processNumber(int num) {
    if (num < 0) {
        throw invalid_argument("Number cannot be negative");
    }
    if (num > 100) {
        throw out_of_range("Number exceeds maximum value");
    }
    if (num == 0) {
        throw runtime_error("Number cannot be zero");
    }
    
    cout << "Processing number: " << num << endl;
}

int main() {
    int numbers[] = {5, -3, 150, 0, 50};
    
    for (int num : numbers) {
        try {
            processNumber(num);
        } 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;
        } catch (...) {
            cout << "Unknown error occurred" << endl;
        }
    }
    
    return 0;
}
Output
Processing number: 5
Invalid argument: Number cannot be negative
Out of range: Number exceeds maximum value
Runtime error: Number cannot be zero
Processing number: 50

Understanding Multiple catch Blocks

This program teaches you how to use Multiple catch Blocks in C++. Multiple catch blocks allow handling different exception types with specific error handling logic. This enables precise error management based on the type of exception thrown.

---

1. What This Program Does

The program demonstrates multiple catch blocks:

Handling different exception types
Specific catch blocks for each type
Catch-all block for unknown exceptions
Processing multiple values with error handling

Multiple catch blocks enable type-specific error handling.

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <stdexcept>
Provides standard exception classes.

---

3. 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!

---

4. Standard Exception Types

Common Types

:

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

How it works

:

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

---

5. 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");

}

How it works

:

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

---

6. Catching Specific Exceptions

Multiple Catch Blocks

:

catch (const invalid_argument& e) {

} catch (const out_of_range& e) {

cout << "Out of range: " << e.what() << endl;

} catch (const runtime_error& e) {

cout << "Runtime error: " << e.what() << endl;

}

    cout << "Invalid argument: " << e.what() << endl;

How it works

:

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

---

7. Catch-All Block

Using catch(...)

:

catch (...) {

}

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

How it works

:

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

---

8. When to Use Multiple Catch Blocks

Best For

:

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)

---

9. 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

---

10. return 0;

This ends the program successfully.

---

Summary

Multiple catch blocks: handle different exception types with specific logic.
Catch blocks checked in order, first matching catch executes.
Standard types: invalid_argument, out_of_range, runtime_error, logic_error.
catch(...): catch-all for any exception type, must be last.
Always catch more specific exceptions before general ones.
Understanding multiple catch blocks enables precise error handling.
Essential for comprehensive error management and type-specific recovery.

This program is fundamental for learning advanced exception handling, understanding exception types, and preparing for robust error management in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Multiple catch Blocks

This C++ program is part of the "Exception Handling Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents