1

相关问题:

这个问题有所不同,因为我不关心可移植性。我对专门用于 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++ 下的异常类型?

4

1 回答 1

3

这是我使用的:

#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;
  }
于 2012-12-13T21:48:07.413 回答