【问题标题】:non-portable way to find exception type in catch (...) for g++在g ++的catch(...)中查找异常类型的非便携式方法
【发布时间】:2013-04-18 06:58:47
【问题描述】:

相关问题:

这个问题有所不同,因为我不关心可移植性。我对专门用于 g++ 甚至特定版本的 g++ (4.6.3) 的代码感兴趣。它不会在生产中使用。

我正在处理具有数千个 throw 语句以及可能有数百个抛出类型的遗留代码。这段代码在近 1000 台机器上运行,每天捕获大约 40 次抛出。不可重复。

在外层,我可以尝试一下 { /.../ } catch (...) { /* catch it */ } 并看到抛出了异常。但是我一直找不到异常的类型,更不用说它是从哪里抛出的了。

我相信信息必须是可用的,因为像下面这样的代码可以工作并打印“Y”:

#include <iostream>
using namespace std;
struct X {};
struct Y {};
struct Z {};
int main(int, char **) {
    try {
        //...
        throw Y();
        //...
    } catch (...) {
        cout << "Caught unknown" << endl;
        try {
            throw;
        } catch (const X &x) {
            cout << "X" << endl;
        } catch (const Y &y) {
            cout << "Y" << endl;
        } catch (const Z &z) {
            cout << "Z" << endl;
        }
    }
}

是否有任何 [non-portable|dirty|nasty|ugly]* 技巧可以在 catch (...) 中识别 g++ 下的异常类型?

【问题讨论】:

    标签: exception g++


    【解决方案1】:

    这是我使用的:

    #include <cxxabi.h>
    
    using std::string;
    string deMangle(const char* const name)
    {
      int status = -1;
      char* const dem = __cxxabiv1::__cxa_demangle(name, 0, 0, &status);
    
      const string ret = status == 0 ? dem : name;
    
      if (status == 0)
        free(dem);
    
      return ret;
    }
    
    string getGenericExceptionInfo()
    {
      const std::type_info* t = __cxxabiv1::__cxa_current_exception_type();
      char const* name = t->name();
    
      return deMangle(name);
    }
    

    用法:

    catch (...)
      {
        std::cerr << "caught: " << getGenericExceptionInfo() << std::endl;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2023-04-08
      • 2011-03-01
      相关资源
      最近更新 更多