在编译器MSVC、GCC、Clang或它们的通用包装器中是否有通用解决方案来捕获异常,例如除以零、分段错误等,可能在“boost”库中?
当然必须是基于每个编译器细微差别的通用解决方案。即使我确实在每个编译器下编写了类似的解决方案,我仍然可以忽略任何细微差别。例如,我可以在带有 SEH 异常的 MSVC 中编写并使用密钥编译它:/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;
}