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

Multiple catch blocks can handle different exception types. Catch blocks are checked in order - first matching catch block executes. Use catch(...) as a catch-all for any exception type. Standard exception types: invalid_argument, out_of_range, runtime_error, logic_error, etc. Always catch more specific exceptions before general ones.

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.

Table of Contents