Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch exceptions for C++ function I called in Objective-C?

My iPad app is using Objective-C for UI, and it calls some C++ functions for computation. Since the C++ code is not well written, it sometimes throw exceptions or causes segmentation fault when tested alone. However, the C++ code is currently under development by someone else so I don't want to change it. Is it possible to catch the exceptions and segmentation fault in my Objective-C code so that I don't need to change the C++ code? I tried the basic try-catch, but it seems not working. (wrapper is the buggy c++ function)

@try {
    wrapper([imageName UTF8String]);
}
@catch (NSException *e) {
    NSLog(@"Error");
}

When I run my app and click the button that calls C++ functions, the simulation crashes and an error message says libc++abi.dylib: terminating with uncaught exception of type NSException

like image 900
user1537085 Avatar asked Nov 19 '13 05:11

user1537085


1 Answers

you can use C++ try-catch with Objective-C++ code (.mm extension)

try {
    wrapper([imageName UTF8String]);
}
catch (...) {
    NSLog(@"Error");
}

In 64-bit processes, you can use @catch(...) to catch everything including C++ exception

@try {
    wrapper([imageName UTF8String]);
}
@catch (...) {
    NSLog(@"Error");
}
like image 133
Bryan Chen Avatar answered Sep 24 '22 23:09

Bryan Chen