Humboldt-Universität zu Berlin - Mathematisch-Naturwissenschaftliche Fakultät - Systemanalyse

Beispiel nested exceptions

text/x-c++src nested.cpp — 1.1 KB

Dateiinhalt

#include <iostream>
#include <string>
#include <exception>

class low_level_ex: public std::exception {
public:
	const char* what() const noexcept {
		return "low level exception";
	}
};

class high_level_exception : public std::exception
                        //, public std::nested_exception
{
public:
    const char* what() const noexcept {
        return "high level exception";
    }
};

void lib_func (int i) {
    try {
        if (i<0) throw low_level_ex();
    }
    catch (...) {
        std::throw_with_nested(high_level_exception()); 
    }
}

void print_ex(const std::exception& e, int level = 0) {
	std::cerr << std::string(level, '\t') << e.what() << "\n";
	try {
        std::rethrow_if_nested(e);
	}
	catch (const std::exception& e) {
		print_ex(e, level + 1);
	}
    catch (const low_level_ex& e) {
		// never reached!
	}
}

void run() {
    try {
        lib_func(2);
        lib_func(-2);
    }
    catch (const std::exception & e) {
        std::throw_with_nested(std::runtime_error("run() failed")); 
    }
}

int main() {
    try {
        run();
    }
    catch (const std::exception & e) {
        print_ex(e);
    }
}