example4_exception_type_info.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
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cxxabi.h>
#include <exception>
#include <stdexcept>
#include <typeinfo>

void print_exception_info(const std::exception& e) {
    const std::type_info& ti = typeid(e);
    int status;
    char* demangled_name = abi::__cxa_demangle(ti.name(), nullptr, nullptr, &status);
    
    std::cout << "Exception type: " << (status == 0 ? demangled_name : ti.name()) << std::endl;
    std::cout << "Exception message: " << e.what() << std::endl;
    
    if (demangled_name) {
        free(demangled_name);
    }
}

int main() {
    try {
        throw std::runtime_error("This is a runtime error");
    } catch (const std::exception& e) {
        print_exception_info(e);
    }

    try {
        throw std::logic_error("This is a logic error");
    } catch (const std::exception& e) {
        print_exception_info(e);
    }

    return 0;
}
Back to cxxabi.h