我创建了一个 C++ 库。我在 iOS 应用程序中使用它。我想到了处理 C++ 库中的异常,为了测试这一点,我创建了一个测试方案并从中调用了 C++ 函数。在c++函数中我故意写了错误的代码。
try
{
int i = 0;
int j = 10/i;
}
catch(std::exception &e){
printf("Exception : %s\n",e.what());
}
但异常从未被捕获,并且应用程序在 - int j = 10/i; 处中断;
请告诉我,在这种情况下如何向我的 C++ 代码添加异常处理?
谢谢。
最佳答案
当遇到被零除时,C++ 不会抛出异常(另请参阅 this 和 this 其他问题)!引用斯特鲁斯特鲁普的话:
low-level events, such as arithmetic overflows and divide by zero, are assumed to be handled by a dedicated lower-level mechanism rather than by exceptions. This enables C++ to match the behaviour of other languages when it comes to arithmetic. It also avoids the problems that occur on heavily pipelined architectures where events such as divide by zero are asynchronous.
“C++ 的设计与演变”(Addison Wesley,1994 年)
所以你必须自己处理这种情况 - 你必须在除法之前检查每个潜在的除数并处理它。
关于XCode iOS 项目中未捕获 C++ 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527751/