我需要创建一些接口(interface),它能够通过代码(int)给我合适的异常。
异常继承:
BaseException : public std::exception {...};
DerivedException1 : public BaseException {...};
DerivedException2 : public BaseException {...};
我需要像 get(int code)
这样的函数来解决这个问题:
try {
int code = foo();
throw get(code);
}
catch(DerivedException1& e) {...}
catch(DerivedException2& e) {...}
catch(BaseException& e) {...}
先谢谢大家了!
最佳答案
throw
按值抛出,因此您可以使用以下方式进行切片:
std::exception& e = /*...*/;
throw e; // throws a std::exception, not possible derived class
那么你可能会这样做:
void as_exception(int error_code)
{
switch (error_code)
{
case 0: return; // Not an error.
case 1: throw DerivedException1();
case 2: throw DerivedException2();
// ...
}
}
用法类似于:
try {
const int code = foo();
as_exception(code);
}
catch (const DerivedException1& e) {...}
catch (const DerivedException2& e) {...}
catch (const BaseException& e) {...}
同样,您可以使用 std::exception_ptr方法如下:
std::exception_ptr as_exception_ptr(int error_code)
{
switch (error_code)
{
case 0: return nullptr; // Not an error.
case 1: return std::make_exception_ptr(DerivedException1());
case 2: return std::make_exception_ptr(DerivedException2());
// ...
}
}
用法类似于:
try {
const int code = foo();
const auto eptr = as_exception_ptr(code);
if (eptr) {
std::rethrow_exception(eptr);
}
}
catch (const DerivedException1& e) {...}
catch (const DerivedException2& e) {...}
catch (const BaseException& e) {...}
关于c++ 如何在运行时通过错误代码给用户一个合适的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59415414/