首页 > 解决方案 > 在 C++ 中转换异常类型

问题描述

我有一些看起来像这样的例外

class ExceptionType1Base : public std::runtime_error {

};

class ExceptionType1Derived1 : public ExceptionType1Base {

};

class ExceptionType1Derived2 : public ExceptionType1Base {

};

还有另一种异常类型

class ExceptionType2Base : public std::runtime_error {
   public:
    int type;
};

class ExceptionType2Derived1 : public ExceptionType2Base {
    ExceptionType2Derived1() {
       type = 1;
    }  

};

class ExceptionType2Derived2 : public ExceptionType2Base {
    ExceptionType2Derived2() {
       type = 2;
    }  
};

我想在捕获它时将一种异常类型转换为另一种类型,例如

ExceptionType1Base convertToType1Exception(ExceptionType2Base& ex) {
     if(ex.type == 1) {
        return ExceptionType1Derived1();
     }

     return ExceptionType1Derived2();
}

然后当我捕获异常时,就像

try {
    ... some code .... 
} catch (const ExceptionType2Base& ex) {
    throw convertToType1Exception(ex);
}

问题是我丢失了转换后异常的派生类型,最终抛出的异常是 ExceptionType1Base,有什么更好的处理方法吗?我想过使用宏进行异常类型转换,但我想知道是否有更好的方法。

标签: c++exceptionc++17

解决方案


您想实现 到 之间的ExceptionType1映射ExceptionType2。您当前的实现不起作用,因为根据 的签名convertToType1Exception,它将始终返回ExceptionType1Base对象。但是请注意,type返回对象的属性将是 1 或 2,具体取决于它是ExceptionType1Derived1还是ExceptionType1Derived2

解决此问题的一种方法是单独捕获 Type1 异常并抛出相应的 Type2 异常。以下是执行此操作的示例。您可以通过添加更多捕获案例来扩展它以获取更多异常。

#include <iostream>
#include <typeinfo>

class ExceptionType1Base
{
};
class ExceptionType1Derived1:public ExceptionType1Base
{
};
class ExceptionType1Derived2:public ExceptionType1Base
{
};

class ExceptionType2Base
{
public:
  ExceptionType2Base ()
  {
  }
  int type;
};

class ExceptionType2Derived1:public ExceptionType2Base
{
public:
  ExceptionType2Derived1 ()
  {
    type = 1;
  }
};
class ExceptionType2Derived2:public ExceptionType2Base
{
public:
  ExceptionType2Derived2 ()
  {
    type = 2;
  }
};

ExceptionType1Derived1
t1d1 ()
{
  throw ExceptionType1Derived1 ();
}

ExceptionType1Derived2
t1d2 ()
{
  throw ExceptionType1Derived2 ();
}

int
main ()
{
  try
  {
    t1d2 ();
    //t1d1();
  } catch (const ExceptionType1Derived1 & ex)
  {
    throw ExceptionType2Derived1 ();
  } catch (const ExceptionType1Derived2 & ex)
  {
    throw ExceptionType2Derived2 ();
  }
  return 0;
}

这里 main 将抛出ExceptionType2Derived2. 如果你打电话t1d1那么ExceptionType1Derived1


推荐阅读