Demonstrating Exception Throwing - C++ Class

C++ examples for Class:Exception Class

Description

Demonstrating Exception Throwing

Demo Code

#include <exception>
#include <iostream>

void throwException() {
    try {//from w ww.  ja  va  2s .c om
        std::cout << "  Function throwException throws an exception\n";
        throw std::exception();
    } catch (std::exception &) {
        std::cout << "  Exception handled in function throwException"
                  << "\n  Function throwException rethrows exception";
        throw;  // rethrow exception for further processing
    }

    std::cout << "This also should not print\n";
}

int main(int argc, const char *argv[]) {
    try {
        std::cout << "\nmain invokes function throwException\n";
        throwException();
        std::cout << "This should not print\n";
    } catch (std::exception &) {
        std::cout << "\n\nException handled in main\n";
    }

    std::cout << "Program control continues after catch in main\n";
    return 0;
}

Result


Related Tutorials