Are there universal solutions to catch exceptions such as divide by zero, segmentation fault, etc. in compilers MSVC, GCC, Clang or universal wrapper for them, may be in "boost" library?
Surely must be a universal solution based on the nuances of each compiler. Even if I did write a similar solution under every compiler, I still can to leave and forget out any nuances. For example I can write in MSVC with SEH-exceptions and compile it with key: /ZHa
#include<iostream>
#include<string>
#ifdef _MSC_VER
#include <windows.h>
#include <eh.h>
class SE_Exception
{
private:
EXCEPTION_RECORD m_er;
CONTEXT m_context;
unsigned int m_error_code;
public:
SE_Exception(unsigned int u, PEXCEPTION_POINTERS pep)
{
m_error_code = u;
m_er = *pep->ExceptionRecord;
m_context = *pep->ContextRecord;
}
~SE_Exception() {}
unsigned int get_error_code() const { return m_error_code; }
std::string get_error_str() const {
switch(m_error_code) {
case EXCEPTION_INT_DIVIDE_BY_ZERO: return std::string("INT DIVIDE BY ZERO");
case EXCEPTION_INT_OVERFLOW: return std::string("INT OVERFLOW");
// And other 20 cases!!!
}
return std::string("UNKNOWN");
}
};
void trans_func(unsigned int u, EXCEPTION_POINTERS* pExp)
{
throw SE_Exception(u, pExp);
}
#else
struct SE_Exception
{
unsigned int get_error_code() const { return 0; }
std::string get_error_str() const { return std::string("Not MSVC compiler"); }
};
#endif
int main() {
#ifdef _MSC_VER
_set_se_translator( trans_func );
#endif
try {
int a = 0;
int b = 1 / a;
std::cout << "b: " << b << std::endl;
} catch(SE_Exception &e) {
std::cout << "SEH exception: (" << e.get_error_code() << ") " << e.get_error_str() << std::endl;
} catch(...) {
std::cout << "Unknown exception." << std::endl;
}
int b;
std::cin >> b;
return 0;
}