I'm new to iOS programming, now I met a problem related to catching the exception code threw from a C++ class.
@try {
myCPPClass myObj ; //this throws integer exception codes
}
@catch (...) { //I want to catch the integer value here, how ??
NSLog(@"Exception:") ;
}
@finally {
}
I knew it maybe not a good practice coding Objective-C in exception catching style, I'd like to know how to make custom exception class for C++ classes in Objective-C ?
Rename your objective-c .m
source files to have the .mm
extension. They will then be compiled as objective-c++ which is fully compatible with objective-c while offering all the facilities of c++.
then you can catch c++ exceptions with the usual
try {
...
}
catch(std::exception& e) {
...
}
construct.
An extension to Richard's answer for those still not catching any exceptions from C++.
Use this instead of try catch
.
@try { }
@catch (...) {
NSLog(@"Exception:");
}
Why?
Objective-C catch clause taking a dynamically typed exception object (@catch(id exception)) can catch any Objective-C exception, but cannot catch any C++ exceptions. So, for interoperability, use @catch(...) to catch every exception and @throw; to rethrow caught exceptions. In 32-bit, @catch(...) has the same effect as @catch(id exception).
Still, not catching any exceptions?
- Don't specify the
-no_compact_unwind
flag.- Specify the -funwind-tables flag if you're including plain C code.
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.