Demonstration stack unwinding during exception handling - C++ Statement

C++ examples for Statement:throw

Description

Demonstration stack unwinding during exception handling

Demo Code

#include <iostream>
#include <stdexcept>

void function3() throw(std::runtime_error) {
    std::cout << "In function 3" << std::endl;
    throw std::runtime_error("runtime_error in function 3");
}
void function2() throw(std::runtime_error) {
    std::cout << "Function3 is called inside function2" << std::endl;
    function3();  // stack unwinding occurs, return control to function1
}
void function1() throw(std::runtime_error) {
    std::cout << "Function2 is called inside function1" << std::endl;
    function2();  // stack unwinding occurs, return control to main
}
int main(int argc, const char *argv[]) {
    try {/*from  w w  w  . j av a  2 s.  c  om*/
        std::cout << "function1 is called inside main" << std::endl;
        function1();  // call function1 which throws runtime_error
    } catch (std::runtime_error &error) {
        std::cout << "Exception occured: " << error.what() << std::endl;
        std::cout << "Exception handled in main" << std::endl;
    }

    return 0;
}

Result


Related Tutorials