How to catch C++ exception code in iOS Objective-C? - c++

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).
- C++ Interoperability
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.
- Addressing Language Exception Crashes

Related

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
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");
}
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");
}
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.
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.

Trying to catch exception in MFC's CString::Format

I am working with a C++ project (that I was not the author of) that has a lot of MFC string formatting functions. Unfortunately, stuff like %d and %s are very close together (including the location of letters d and s on the keyboard) that one can be transposed with another. So I may at times witness a code line as such:
CString s;
s.Format(L"Value v=%s", 100); //Should've been %d instead
This results in a hard crash of the process, that is very hard to locate & isolate in the final project. So I was thinking to wrap the Format function in my own override and catch the exception & log it before it is thrown as unhandled exception.
So I employed the following construct:
__try
{
//Do the Format function here
}
__except(1)
{
//Log the error, etc.
}
But unfortunately the construct above did not catch the exception from the first code chunk, so I got VS 2008 C++ debugger kick in and show this:
I then tried this:
try
{
//Do the Format function here
}
catch(int e)
{
//Do the logging
}
But that didn't catch it either.
So how can I catch that fault?
PS. And I have a second question. Is there an easy way to override an MFC function, like Format for instance?
MFC throws CException pointers, so you could try this:
try
{
// Do the Format function here
}
catch(CException* e)
{
// Do the logging then free the exception
if (m_bThrowExceptionAgain)
throw; // Do not delete e
else
e->Delete();
}
You have to delete the exception object once you have caught it as shown in the example. Also make sure you have C++ exceptions enabled in your compiler. See http://msdn.microsoft.com/en-us/library/0e5twxsh.aspx for more information.
As others have already said low-level exceptions (like access violations) are not the same as C++ exceptions. They fall under the term Structured Exception Handling and would require other means to catch, at least by default.
It's possible to change compiler settings (at least in Visual Studio) to make it wrap those exceptions into something that C++ try/catch statements can handle, but as I recall that loses the details of what the SEH exception was and where it came from.
One way or another you could probably get exceptions to work well enough to help track down these issues, but there is also another way: Use static code analysis.
While standard C++ compilers don't normally verify format/printf-style calls, there are various tools that will. In fact some recent versions/editions of Visual Studio come with a code analysis tool, although it may not have been available in VS 2008 which you mentioned. So it might be worthwhile for you to do some research and see if you can get a hold of some kind of code analysis tool which could then catch all the CString::Format mistakes during analysis/compile-time rather than run-time.
You can use _set_se_translator() to convert SEH exceptions like access violation to C++ exceptions which you can then catch with except().
Some sample code: http://www.codeproject.com/Articles/422/SEH-and-C-Exceptions-catch-all-in-one

Why are my C++ exceptions not being caught?

I have some C++ code that uses a very standard exception pattern:
try {
// some code that throws a std::exception
}
catch (std::exception &e) {
// handle the exception
}
The problem is that the exceptions are not being caught and I cannot figure out why.
The code compiles to a static library in OS X (via Xcode). The library is linked into a Cocoa application, with a call to the function in question happening via an Objective-C++ thunk. I suspect that the interplay between Objective-C and C++ is the culprit but all my attempts to pin this down have failed.
I have not been able to create a simple example that reproduces this behavior in a simple example. When I take the relevant code out of the context of my big program everything works.
Can anyone suggest why my exceptions are not being caught?
C++ allows you a variety of options for catching: value, reference or pointer.
Note that this code only catches std::exceptions passed by reference or value:
try {
// some code that throws a std::exception
}
catch (std::exception &e) {
// handle the exception
}
It's likely that the exception is being passed by pointer:
catch (std::exception* e)
Check the code that is throwing the exception, and see how it's doing it.
As Mark points out, if you catch by value instead of by reference you risk slicing your object.
Try a catch(...) {} block, see if an exception is really thrown.
I suspect that the interplay between Objective-C and C++ is the culprit but all my attempts to pin this down have failed.
You're probably right, although it's hard to track down.
First, GCC explicitly does not allow you to throw exceptions in Objective C++ and catch them in C++ ("when used from Objective-C++, the Objective-C exception model does not interoperate with C++ exceptions at this time. This means you cannot #throw an exception from Objective-C and catch it in C++, or vice versa (i.e., throw ... #catch).")
However, I think you're describing a case where Objective C++ calls C++ code, the C++ code throws and you're hoping for C++ code to catch the exception. Unfortunately I'm having difficulty finding documentation for this specific case. There is some hope because, "It is believed to be safe to throw a C++ exception from one file through another file compiled for the Java exception model, or vice versa, but there may be bugs in this area." If they can do it for Java, there is a chance they can do it for Objective C++.
At the very least, you'll need to specify -fexceptions at compile time ("you may need to enable this option when compiling C code that needs to interoperate properly with exception handlers written in C++"). Again, that doesn't specifically mention Objective C++ but it may apply.
One little known gotcha with exceptions relates to the access of the base class.
If you are actually throwing a class that derives privately from std::exception then the std::exception handler will not be chosen.
For example:
#include <iostream>
class A { };
class B : private A { } ;
int main ()
{
try
{
throw B ();
}
catch (A & )
{
std::cout << "Caught an 'A'" << std::endl;
}
catch (B & )
{
std::cout << "Caught an 'B'" << std::endl;
}
}
Usually, such an order of handlers would result in the 'B' handler never being selected, but in this case 'B' dervies from 'A' privately and so the catch handler for type 'A' is not considered.
I can offer two theories:
the exception gets caught before it comes your catch clause; any function on the stack might be the culprit. As Michael proposes, try catching everything.
exception unwinding fails to locate your handler. To analyze this in more detail, you would have to step through the exception unwinding code, which is very hairy. See whether compiling the Objective-C code with -fobjc-exceptions helps.
This might be a long shot, but in Visual Studio's compiler settings there is an option to switch off exceptions entirely. Perhaps there's something similar in GCC / XCode.
C++ exceptions can be just about anything, quite frequently a char*. As suggested before add catch (...) to at least get it to break and see what's going on.
Thanks for the input from everyone. Those are good suggestions for anyone who runs into a similar problem. It's working now, but I'm not 100% sure which of various changes I made caused things to become sane again. Once again, the approach of simplifying down to something that works and building back up from there paid off.
One thing that wasn't mentioned in the responses, and which I think was part of my confusion, is to make sure that the handler makes it obvious that it actually caught the exception. I think that in some of my formulations of the handler it was masking that fact and passing the exception on to a higher level handler.

Can't catch exception!

I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application!
The class PyMonitor.cc describes the swig interface to the desired class, Monitor.
Monitor's constructor throws an exception if it fails to connect. I'd like to handle this exception in PyMonitor, e.g.:
PyMonitor.cc:
#include "Monitor.h"
// ...
bool PyMonitor::connect() {
try {
_monitor = new Monitor(_host, _calibration);
} catch (...) {
printf("oops!\n");
}
}
// ...
However, the connect() method never catches the exception, I just get a "terminate called after throwing ..." error, and the program aborts.
I don't know too much about swig, but it seems to me that this is all fine C++ and the exception should propagate to the connect() method before killing the program.
Any thoughts?
You have to forward the exceptions to Python if you want to parse them there.
See the SWIG Documentation.
In order to forward exceptions, you only have to add some code in the SWIG interface (.i) file. Basically, this can be anywhere in the .i file.
All types of exceptions should be specified here, and SWIG only catches the listed exception types (in this case std::runtime_error, std::invalid_argument, std::out_of_range), all other exceptions are caught as unknown exceptions (and are thus forwarded correctly!).
// Handle standard exceptions.
// NOTE: needs to be before the %import!
%include "exception.i"
%exception
{
try
{
$action
}
catch (const std::runtime_error& e) {
SWIG_exception(SWIG_RuntimeError, e.what());
}
catch (const std::invalid_argument& e) {
SWIG_exception(SWIG_ValueError, e.what());
}
catch (const std::out_of_range& e) {
SWIG_exception(SWIG_IndexError, e.what());
}
catch (...) {
SWIG_exception(SWIG_RuntimeError, "unknown exception");
}
}
I'm not familiar with swig, or with using C++ and Python together, but if this is under a recent version of Microsoft Visual C++, then the Monitor class is probably throwing a C structured exception, rather than a C++ typed exception. C structured exceptions aren't caught by C++ exception handlers, even the catch(...) one.
If that's the case, you can use the __try/__except keywords (instead of try/catch), or use the _set_se_translator function to translate the C structured exception into a C++ typed exception.
(Older versions of MSVC++ treated C structured exceptions as C++ int types, and are caught by C++ handlers, if I remember correctly.)
If this isn't under Microsoft Visual C++, then I'm not sure how this could be happening.
EDIT: Since you say that this isn't MSVC, perhaps something else is catching the exception (and terminating the program) before your code gets it, or maybe there's something in your catch block that's throwing another exception? Without more detail to work with, those are the only cases I can think of that would cause those symptoms.
It's possible that a function called directly or indirectly by the Monitor constructor is violating its exception specification and doesn't allow std::bad_exception to be thrown. If you haven't replaced the standard function for trapping this, then it would explain the behaviour that you are seeing.
To test this hypothesis you could try defining your own handler:
void my_unexpected()
{
std::cerr << "Bad things have happened!\n";
std::terminate();
}
bool PyMonitor::connect() {
std::set_unexpected( my_unexpected );
try {
_monitor = new Monitor(_host, _calibration);
} catch (...) {
printf("oops!\n");
}
}
If you get the "Bad things have happened!" error message then you have confirmed that this is the case, but unfortunately there may not be a lot that you can do. If you're 'lucky', you may be able to throw an exception from my_unexpected that is allowed by the exception specification of the function that is currently failing, but in any case your unexpected handler is not allowed to terminate normally. It must throw or otherwise terminate.
To fix this you really need to get into the called code and either correct it so that the exception specification is not violated, either by fixing the specification itself or by fixing the code so that it doesn't throw the exception that isn't expected.
Another possibility is that an exception is being thrown during stack unwinding caused by the original exception being thrown. This also would cause termination of the process. In this case, although you can replace the standard terminate function, you have no option but to abort the program. A terminate handler isn't allowed to throw or return, it must terminate the program.

C++ catching all exceptions

Is there a c++ equivalent of Java's
try {
...
}
catch (Throwable t) {
...
}
I am trying to debug Java/jni code that calls native windows functions and the virtual machine keeps crashing. The native code appears fine in unit testing and only seems to crash when called through jni. A generic exception catching mechanism would prove extremely useful.
try{
// ...
} catch (...) {
// ...
}
will catch all C++ exceptions, but it should be considered bad design. You can use c++11's new current_exception mechanism, but if you don't have the ability to use c++11 (legacy code systems requiring a rewrite), then you have no named exception pointer to use to get a message or name. You may want to add separate catch clauses for the various exceptions you can catch, and only catch everything at the bottom to record an unexpected exception. E.g.:
try{
// ...
} catch (const std::exception& ex) {
// ...
} catch (const std::string& ex) {
// ...
} catch (...) {
// ...
}
Someone should add that one cannot catch "crashes" in C++ code. Those don't throw exceptions, but do anything they like. When you see a program crashing because of say a null-pointer dereference, it's doing undefined behavior. There is no std::null_pointer_exception. Trying to catch exceptions won't help there.
Just for the case someone is reading this thread and thinks he can get the cause of the program crashes. A Debugger like gdb should be used instead.
This is how you can reverse-engineer the exception type from within catch(...) should you need to (may be useful when catching unknown from a third party library) with GCC:
#include <iostream>
#include <exception>
#include <typeinfo>
#include <stdexcept>
int main()
{
try {
throw ...; // throw something
}
catch(...)
{
std::exception_ptr p = std::current_exception();
std::clog <<(p ? p.__cxa_exception_type()->name() : "null") << std::endl;
}
return 1;
}
and if you can afford using Boost you can make your catch section even simpler (on the outside) and potentially cross-platform
catch (...)
{
std::clog << boost::current_exception_diagnostic_information() << std::endl;
}
try {
// ...
} catch (...) {
// ...
}
Note that the ... inside the catch is a real ellipsis, ie. three dots.
However, because C++ exceptions are not necessarily subclasses of a base Exception class, there isn't any way to actually see the exception variable that is thrown when using this construct.
it is not possible (in C++) to catch all exceptions in a portable manner. This is because some exceptions are not exceptions in a C++ context. This includes things like division by zero errors and others. It is possible to hack about and thus get the ability to throw exceptions when these errors happen, but it's not easy to do and certainly not easy to get right in a portable manner.
If you want to catch all STL exceptions, you can do
try { ... } catch( const std::exception &e) { ... }
Which will allow you do use e.what(), which will return a const char*, which can tell you more about the exception itself. This is the construct that resembles the Java construct, you asked about, the most.
This will not help you if someone is stupid enough to throw an exception that does not inherit from std::exception.
In short, use catch(...). However, note that catch(...) is meant to be used in conjunction with throw; basically:
try{
foo = new Foo;
bar = new Bar;
}
catch(...) // will catch all possible errors thrown.
{
delete foo;
delete bar;
throw; // throw the same error again to be handled somewhere else
}
This is the proper way to use catch(...).
it is possible to do this by writing:
try
{
//.......
}
catch(...) // <<- catch all
{
//.......
}
But there is a very not noticeable risk here: you can not find the exact type of error that has been thrown in the try block, so use this kind of catch when you are sure that no matter what the type of exception is, the program must persist in the way defined in the catch block.
You can use
catch(...)
but that is very dangerous. In his book Debugging Windows, John Robbins tells a war story about a really nasty bug that was masked by a catch(...) command. You're much better off catching specific exceptions. Catch whatever you think your try block might reasonably throw, but let the code throw an exception higher up if something really unexpected happens.
Let me just mention this here: the Java
try
{
...
}
catch (Exception e)
{
...
}
may NOT catch all exceptions! I've actually had this sort of thing happen before, and it's insantiy-provoking; Exception derives from Throwable. So literally, to catch everything, you DON'T want to catch Exceptions; you want to catch Throwable.
I know it sounds nitpicky, but when you've spent several days trying to figure out where the "uncaught exception" came from in code that was surrounded by a try ... catch (Exception e)" block comes from, it sticks with you.
Well, if you would like to catch all exception to create a minidump for example...
Somebody did the work on Windows.
See http://www.codeproject.com/Articles/207464/Exception-Handling-in-Visual-Cplusplus
In the article, he explains how he found out how to catch all kind of exceptions and he provides code that works.
Here is the list you can catch:
SEH exception
terminate
unexpected
pure virtual method call
invalid parameter
new operator fault
SIGABR
SIGFPE
SIGILL
SIGINT
SIGSEGV
SIGTERM
Raised exception
C++ typed exception
And the usage:
CCrashHandler ch;
ch.SetProcessExceptionHandlers(); // do this for one thread
ch.SetThreadExceptionHandlers(); // for each thred
By default, this creates a minidump in the current directory (crashdump.dmp)
Be aware
try{
// ...
} catch (...) {
// ...
}
catches only language-level exceptions, other low-level exceptions/errors like Access Violation and Segmentation Fault wont be caught.
A generic exception catching mechanism
would prove extremely useful.
Doubtful. You already know your code is broken, because it's crashing. Eating exceptions may mask this, but that'll probably just result in even nastier, more subtle bugs.
What you really want is a debugger...
Can you run your JNI-using Java application from a console window (launch it from a java command line) to see if there is any report of what may have been detected before the JVM was crashed. When running directly as a Java window application, you may be missing messages that would appear if you ran from a console window instead.
Secondly, can you stub your JNI DLL implementation to show that methods in your DLL are being entered from JNI, you are returning properly, etc?
Just in case the problem is with an incorrect use of one of the JNI-interface methods from the C++ code, have you verified that some simple JNI examples compile and work with your setup? I'm thinking in particular of using the JNI-interface methods for converting parameters to native C++ formats and turning function results into Java types. It is useful to stub those to make sure that the data conversions are working and you are not going haywire in the COM-like calls into the JNI interface.
There are other things to check, but it is hard to suggest any without knowing more about what your native Java methods are and what the JNI implementation of them is trying to do. It is not clear that catching an exception from the C++ code level is related to your problem. (You can use the JNI interface to rethrow the exception as a Java one, but it is not clear from what you provide that this is going to help.)
For the real problem about being unable to properly debug a program that uses JNI (or the bug does not appear when running it under a debugger):
In this case it often helps to add Java wrappers around your JNI calls (i.e. all native methods are private and your public methods in the class call them) that do some basic sanity checking (check that all "objects" are freed and "objects" are not used after freeing) or synchronization (just synchronize all methods from one DLL to a single object instance). Let the java wrapper methods log the mistake and throw an exception.
This will often help to find the real error (which surprisingly is mostly in the Java code that does not obey the semantics of the called functions causing some nasty double-frees or similar) more easily than trying to debug a massively parallel Java program in a native debugger...
If you know the cause, keep the code in your wrapper methods that avoids it. Better have your wrapper methods throw exceptions than your JNI code crash the VM...
If you are looking for Windows-specific solution then there is structured exception handling:
https://learn.microsoft.com/en-us/cpp/cpp/try-except-statement
The code looks as follows
__try
{
// code here may throw or make access violation
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
// after exception code here, e.g. log the error
}
It will catch not only C++ exceptions but also access violations or other system exceptions.
Well this really depends on the compiler environment.
gcc does not catch these.
Visual Studio and the last Borland that I used did.
So the conclusion about crashes is that it depends on the quality of your development environment.
The C++
specification says that catch(...) must catch any exceptions, but it doesn't in all cases.
At least from what I tried.