example3_rethrowing_exceptions.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <stdexcept>

void processData(int data) {
    try {
        if (data < 0) {
            throw std::out_of_range("Data must be non-negative");
        }
        std::cout << "Processing data: " << data << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error in processData: " << e.what() << std::endl;
        throw; // Rethrow the caught exception
    }
}

int main() {
    try {
        processData(5);
        processData(-1);
    } catch (const std::exception& e) {
        std::cerr << "Caught in main: " << e.what() << std::endl;
    }
    return 0;
}
Back to throw