gpt4 book ai didi

c++ - 当类定义不可见时捕获异常

转载 作者:太空狗 更新时间:2023-10-29 22:55:08 27 4
gpt4 key购买 nike

我正在处理损坏的输入文件导致抛出异常的问题。异常类在实现文件中定义,因此对我不可见。它继承自 std::exception

我尝试简单地向前声明异常类,因为我只是通过引用捕获它。但是,这给了我一个error: invalid use of incomplete type 编译器错误(在 Linux 上使用 GCC 6.2)。我想编译器需要完整的异常对象类型,以便它可以在需要时重新抛出异常。

所以这就是我想做的:

// library.cpp

namespace FOO {

struct SomeException : public std::exception
{
// string member, virtual dtor, ctor taking one arg and virtual what()
};

void doStuff() {
}

}


// my main.cpp
namespace FOO
{
struct SomeException;
}

int main()
{
try
{
FOO::doStuff();
}
catch (FOO::SomeException& e)
{
// ignore e, but I know where it came from so log
// an appropriate message
}
catch (std::exception& e)
{
// most other exceptions, log `what()` message
}
catch(...)
{
// tell user to contact customer support
}
}

仅打印 what() 消息不适合我的上下文。

我可以要求其他团队将他们的异常类定义移到标题中。这可能是一个缓慢的过程。我想我也可以对 what() 消息进行字符串比较,但这看起来很难看。

还有其他选择吗?

(顺便说一句,我在 Google 上看不到任何提及,但这似乎是一种反模式,即“仅抛出异常”)。

最佳答案

如果您无法访问原始类,您将无法正确捕获它:

C++ standard / [except.handle]:

The exception-declaration in a handler describes the type(s) of exceptions that can cause that handler to be entered. The exception-declaration shall not denote an incomplete type, an abstract class type, or an rvalue reference type. The exception-declaration shall not denote a pointer or reference to an incomplete type, other than [cv void*].

所以没有理想和干净的解决方案。但也许可以接受的解决方法:派生自 std::exception 的类是多态的。所以你可以考虑使用 typeid() (最终与 type_index 结合)识别 catch (std::exception& e) block 中的真实类型。

恕我直言,当 .what() 不是替代方案时,区分未知异常应该是一种可接受的方法。然而,不便之处在于 type_info 数据(例如 typeid(e).name())的值未在标准中定义,这使得任何硬编码值不可携带。

概念验证:

//somewhere
class MyExcept : public std::exception { };

...

// somewhere else
try {
throw std::exception();
} catch (std::exception &e) {
std::cout <<"case 1: " << typeid(e).name() << std::endl;
}

try {
throw MyExcept();
} catch (std::exception &e) {
std::cout <<"case 2: "<< typeid(e).name() << std::endl;
}

Online demo

关于c++ - 当类定义不可见时捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53120651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com