在我希望异常被捕获的情况下,异常没有被捕获。代码在 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 中运行良好。
谢谢,
巴里
最佳答案
您的代码无法按照编写的方式进行编译。当我如下更改它以添加所需的包含、变量等时,它会按预期打印“异常”(g++ 4.2 和 4.5)。您能否向我们展示导致问题的完整真实代码?
#include <exception>
#include <stdexcept>
#include <iostream>
int x = 0;
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
std::cout << "exception" << std::endl;
}
catch( ... ){
// But the exception is caught here
std::cout << "..." << std::endl;
}
return 0;
}
int main()
{
foo();
return 0;
}
关于基类未捕获 C++ 派生类异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9265329/