[英]c++ exception(std::bad_alloc) handle in objc++
As title, throw exception in c++: 作为标题,在c ++中引发异常:
class TestCpp
{
public:
TestCpp (){
NSLog(@"TestCpp init.");
throw "simple exception."; // or throw std::bad_alloc();
}
~TestCpp(){
NSLog(@"TestCpp fini.");
}
};
And catch it like this: 并像这样捕获它:
@try{
TestCpp o;
}
@catch(NSException* ex) {
NSLog(@"exception: %@", ex.reason);
}
@catch(...){
NSLog(@"unknown exception.");
}
But that can not work. 但这行不通。 Moreover, in objc++, if no way to handle a exception thrown by C++, how can we handle C++ instance construct exceptions, like std::bad_alloc? 而且,在objc ++中,如果没有办法处理C ++引发的异常,我们如何处理C ++实例构造异常,如std :: bad_alloc?
Most Objective-C libraries (esp. UIKit) do not support exceptions and their use is strongly discouraged by Apple. 大多数Objective-C库(特别是UIKit)都不支持异常,Apple强烈建议不要使用它们。 Catching exceptions in Objective-C code can lead to various bugs. 在Objective-C代码中捕获异常可能导致各种错误。
If you want to use C++ code in your Objective-C class then you have to use Objective-C++ by naming the file .mm
instead of .m
如果要在Objective-C类中使用C ++代码,则必须通过命名文件.mm
而不是.m
来使用Objective-C ++。
Have a long time investigate, I get some code: 经过很长时间的调查,我得到了一些代码:
Type* obj_ptr = new (std::nothrow) Type;
if(obj_ptr==nullptr) {
@throw NSMallocException;
}
......
And so everything OK. 这样,一切正常。 Because NSMallocException has been initialized as process startup. 因为NSMallocException已初始化为进程启动。 Some other resource acquire failure can handle as follow: 其他一些资源获取失败可以按以下方式处理:
Resource* resource_handle = acquire(Resource);
if(resource_handle==nullptr) {
@throw NSXxxGenericException;
}
......
Or you can initialize some special NSXxxException for your custom need. 或者,您可以根据自己的需要初始化一些特殊的NSXxxException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.