Reputation: 404
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
Upvotes: 8
Views: 7276
Reputation: 46598
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");
}
Upvotes: 9
Reputation: 8012
Your code as written should catch NSExceptions thrown by the C++ code as long as all of the code in the stack trace between the throw and the catch is compiled with exceptions enabled. Check your compiler flags.
You cannot catch segmentation faults with an exception handler. It is not impossible to catch them with a signal handler, but it's generally impossible to do anything useful to recover so we don't recommend it.
Upvotes: 1
Reputation: 3017
I am not sure if this is what you are looking for, but maybe that helps too.
You can add exception breakpoint if you debug your app with Xcode
.
Go to Breakpoint Navigator
, find the little "+"
sign at the bottom, click and choose Add Exception Breakpoint
. From now when your app throws an exception, Xcode
shows you which line throws it. By default Breakpoint Exception
works for Objective-C
and C++
exceptions, you can change that by right-clicking the exception in Breakpoint Navigator
.
Upvotes: 1
Reputation: 1964
Your can write cpp code in your file (.mm extension instead of .m) and use a C++ try/catch like this:
#include <stdexcept>
try
{
wrapper([imageName UTF8String]);
}
catch (const std::exception & e)
{
NSLog(@"Error");
}
Upvotes: 2