c++ - 在 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,有什么更好的处理方法吗?我想过使用宏进行异常类型转换,但我想知道是否有更好的方法。
解决方案
您想实现 到 之间的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
。
推荐阅读
- amazon-web-services - AWS Lambda 通过 SNS 触发 | 百万条消息
- c++ - 为什么 winsock 没有 64 位 API?
- c - 将结构中的字符串传递给函数并返回
- flutter - 如何在flutter web中打开wxminiProgram?
- javascript - 通过 javascript 在 Blazor 中更改输入值不会更改它的绑定属性值
- sql - 错误 - ORA-00979: 不是 GROUP BY 表达式,但在我删除 f.film_no AS "Film Number" 时有效
- python - 如何在其他文件中使用事件?
- mysql - 从另一个模型验证其值的表单的验证错误引发
- sql - 子查询返回超过 1 个值 - STIntersects
- spring - Spring State Machine:可能的事件