简体   繁体   中英

c++ exception(std::bad_alloc) handle in objc++

As title, throw exception in 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?

Most Objective-C libraries (esp. UIKit) do not support exceptions and their use is strongly discouraged by Apple. Catching exceptions in Objective-C code can lead to various bugs.

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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