【发布时间】:2012-02-13 17:50:06
【问题描述】:
在我希望它们被捕获的情况下,异常不会被捕获。该代码位于 1 个 cpp 文件中的 1 个函数中,该文件由 GCC 4.2 编译为静态库,然后链接到 Cocoa 应用程序中。有问题的代码是
class runtime_error : public exception{
// More code
};
int foo( void ){
try {
if( x == 0 ){
throw std::runtime_error( "x is 0" );
}
}
catch( std::exception & e ){
// I expect the exception to be caught here
}
catch( ... ){
// But the exception is caught here
}
}
我可以修改代码为
int foo( void ){
try {
if( x == 0 ){
throw std::runtime_error( "x is 0" );
}
}
catch( std::runtime_error & e ){
// exception is now caught here
}
catch( … ){
}
}
代码的第二个版本只解决了 runtime_error 异常的问题,而不是其他可能从 std::exception 派生的异常类。知道有什么问题吗? 请注意,代码的第一个版本在 Visual Studio 中运行良好。
谢谢,
巴里
【问题讨论】:
-
当你已经存在一个
runtime_error类时,你有什么理由定义你自己的类吗? -
异常应该被捕获。 ideone.com/dl0Dm 更新您的 GCC 并查看错误是否仍然存在
-
您向我们展示的代码无法编译。请提供一个简短的、独立的完整示例。 sscce.org
-
关于 std::runtime_error 的定义有些混乱。我实际上并没有定义它。我只是表明它是从 std::exception 公开派生的,因此应该捕获异常。
-
我发现是第三方库导致了这个问题。如果我链接库(但不调用它的任何代码),则会出现问题。如果我不链接第 3 方库,则不会出现问题。知道如何链接第 3 方静态库会导致此问题吗?谢谢