繁体   English   中英

来自 c++ 的“runtime_error”未在 iOS 中捕获

[英]'runtime_error' from c++ not captured in iOS

在我的 iOS 项目中,我使用了 C++ 模块。 C++ 模块在某些情况下会抛出异常,而 Objective C++ 包装器无法捕获它。 例如

这是我的HelloWorld.h

#include <string>
using namespace std;

class HelloWorld{
public:
    string helloWorld();
};

#endif

实现HelloWorld.cpp

#include "HelloWorld.h"

string HelloWorld::helloWorld(){
    throw (std::runtime_error("runtime_error")); // Throwing exception to test
    string s("Hello from CPP");
    return s;
}

目标 C++ 包装器HelloWorldIOSWrapper.h

#import <Foundation/Foundation.h>

@interface HelloWorldIOSWrapper:NSObject

- (NSString*)getHello;

@end

#endif /* HelloWorldIOSWrapper_h */

实现HelloWorldIOSWrapper.mm

#import "HelloWorldIOSWrapper.h"
#include "HelloWorld.h"

@implementation HelloWorldIOSWrapper

- (NSString*)getHello{
    try {
        HelloWorld h;
        NSString *text=[NSString stringWithUTF8String: h.helloWorld().c_str()];
        return text;
    } catch (const std::exception & e) {
        NSLog(@"Error %s", e.what());
    }
    return nil;
}

@end

#import "HelloWorldIOSWrapper.h"被添加到Bridging-Header

现在,当我尝试从控制器调用getHello()时,应用程序崩溃并在日志中留下以下消息

libc++abi: terminating with uncaught exception of type std::runtime_error: runtime_error
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
terminating with uncaught exception of type std::runtime_error: runtime_error

我希望异常必须在包装器中被捕获,但是,不知道为什么它没有被捕获导致应用程序崩溃。 我想念什么?

C++ 互操作性

在 64 位进程中,Objective-C 异常 (NSException) 和 C++ 异常是可互操作的。 具体来说,当异常机制展开异常时,C++ 析构函数和Objective-C @finally 块会受到尊重。 此外,默认的 catch 子句——即 catch(...) 和 @catch(...)——可以捕获并重新抛出任何异常

另一方面,采用动态类型异常对象 (@catch(id exception)) 的 Objective-C catch 子句可以捕获任何 Objective-C 异常,但不能捕获任何 C++ 异常。 因此,为了互操作性,使用@catch(...) 来捕获每个异常并使用@throw; 重新抛出捕获的异常。 在 32 位中,@catch(...) 与 @catch(id exception) 具有相同的效果。

@try {
} 
@catch (...) {
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM