How to catch exceptions (gcc arm c++) - c++

I use marmalade sdk and there is no support for structured exceptions handling. I need to catch any exception (null pointer, devision by zero or any else) and do some actions before app will crashed (send crash report). How can I do this in native c++ under gcc-arm compiller?

I need to catch any exception
To do so you can use the ellipsis syntax of catch:
try {
doStuff(); // May throw
}
// catch all exceptions derived from std::exception
catch(const std::exception& ex) {
std::cerr << "Caught exception: '" << ex.what() << "'" << std::endl;
}
catch(...) { // catch everything but unkown
}
Also ensure that your build system doesn't suppress exceptions and RTTI explicitly with the -fno-exceptions and -fno-rtti compiler flags.

I've already asked it here. I tried it with the flag enable-exceptions=1 in options. But it never worked for me. There was a thread on Marmalade regarding the exception handling and it was mentioned there that Marmalade doesn't support them and it was demanded by the community to include this.

Related

Can you wrap one exception inheritance hierarchy into another? --or, another clean way to deal with this?

Suppose I have two inheritance hierarchies I'm dealing with in C++. One inherits from std::exception (new hierarchy), and the other inherits from Exception (legacy C++ Builder VCL base exception class). If I call code that may throw either type of exception, I have to write code like this:
try {
// do stuff....
Function1();
Function2();
} catch (std::exception &ex) {
std::cout << "STL exception caught: " << ex.what() << std::endl;
} catch (Exception &ex) {
std::cout << "Legacy exception caught: " << ex.Message.c_str() << std::endl;
} catch (SomeOtherVendorLibraryException &ex) {
// etc.
}
The problem is that each caller needs to have all these catch clauses to try to get every last type of exception, since C++ has no one true, enforced exception base class you can use as a catch-all (e.g. System.Exception class in C#). (catch (...) is a non-starter since you don't have a way of knowing what you caught, and some dangerous system exceptions, like access violations, could be caught as well which are better left untrapped.)
I would like to wrap these "legacy" exceptions into a class in the std::exception hierarchy. This concept of wrapping 3rd-party exceptions into your own exception system isn't entirely unprecedented. For example, the .NET Framework wraps broad sets of errors in other systems (e.g. COMException). Ideally, I'd like to see something like this:
class LegacyException : public std::runtime_error {
public:
// construct STL exception from legacy exception
LegacyException(const Exception &ex) : std::runtime_error(ex.Message.c_str()) {}
};
try {
// In reality, this throw will happen in some function we have no control over.
throw Exception("Throwing legacy exception!");
} catch (std::exception &ex) {
// Ideally, the compiler would use the LegacyException constructor
// to cast the thrown Exception to a LegacyException, which ultimately
// inherits from std::exception.
std::cout << ex.what() << std::endl;
}
Understandably, the exception is never caught - it would be asking quite a bit of magic from the compiler for it to catch it.
Is there a solution that might be similar to the above for wrapping a legacy exception, and achieves these goals?
One "catch" clause or similar, so that general exception handling logic need only be written once.
Logic for converting from one exception type to another must be centralized.
Avoids macros if possible.
No use of lambda functions.
Having worked with BC++Builder I have met the same problem, and macros seemed to be the only solution at the time.
The "cleaner" (hum...) solution is probably a "double-try-catch": the inner try-catch converts your legacy exception into a standard class, and the outer one actually handles the exception.
I don't have the code at hand (it's been years) but basically it boils down to:
#define DTRY try { try
#define DCATCH catch (Exception& e) { throw LegacyException(e); } } catch
DTRY {
...
}
DCATCH(std::exception& e) {
// handle the exception
}
Yes I know it's ugly, but when I worked with Borland I didn't find anything better. Fact is, at that time Borland was awfully non-standard and I have no idea how it evolved since, maybe you can do better nowadays. Hope this helps anyway.

c++ catch error raised by PPL parallel_for

I have written this piece of code to catch error launched by ppl
try
{
parallel_for (m_row_start, m_row_end + 1, [&functionEvaluation,varModel_,this](int i)
{
// do things
});
}
catch(const std::exception error_)
{
QString t(error_.what());
}
try
{
return functionEvaluation.combine(plus<double>());
}
catch(const std::exception error_)
{
QString t(error_.what());
}
No error is caught although I have strong suspicion that it does have exception raised (a larger try{}catch(...){} it catching an std::exception, with no clear message.
I am right with my syntax for catching exception raised in ppl code?
Your syntax is correct although there's no reason you couldn't catch by reference to avoid unnecessary copying of the exception object:
catch(const std::exception & error_)
Check that the exception thrown actually derives from std::exception.
The PPL will only allow exceptions to propagate once all the threads have completed, could you have a thread which is still running preventing you from seeing the exception?
For debugging purposes, you could add an extra catch block:
catch(...)
{
cout << "Unknown exception" << endl;
}
Just to check if you are getting any kind of exception thrown, however I wouldn't leave this in production code because there's no way to usefully do anything with the exception.
First, check what is thrown. If you mistype the catch, it will not react. Maybe it simply is the CONST marker? const-type is not the same as non-const-type, but I actually don't remember well if catches are const-volatile-sensitive.
Second, unless strong reasons arise, always catch by reference:
catch(std::exception& error)
If you do not, then an exception copying will occur: http://www.parashift.com/c++-faq/what-to-catch.html By copying I mean object-copying, not re-raising;)

ellipsis try catch on c++

Can an ellipsis try-catch be used to catch all the errors that can lead to a crash? Are there are any anomalies?
try
{
//some operation
}
catch(...)
{
}
No, it'll only catch C++ exceptions, not things like a segfault, SIGINT etc.
You need to read up about and understand the difference between C++ exceptions and for want of a better word, "C-style" signals (such as SIGINT).
If the code inside try/catch block crashed somehow, the program is anyway in a non-recoverable state. You shouldn't try to prevent the crash, the best that the program can do is just let the process crash.
The "anomaly" is in the fact that your code only catches the exceptions, and not the errors. Even if the code is exception-safe (which may be not the case, if you are trying to work-around its mistakes by a try/catch block), any other inner error may bring the program into irrecoverable state. There is simply no way to protect the program from it.
Addition: look at this article at "The Old New Thing" for some insights.
It is the Catch All handler.
It catches all the C++ exceptions thrown from the try block. It does not catch segfault and other signals that cause your program to crash.
While using it, You need to place this handler at the end of all other specific catch handlers or it all your exceptions will end up being caught by this handler.
It is a bad idea to use catch all handler because it just masks your problems and hides the programs inability by catching all(even unrecognized) exceptions. If you face such a situation you better let the program crash, and create a crash dump you can analyze later and resolve the root of the problem.
It catches everything that is thrown, it is not limited to exceptions. It doesn't handle things like windows debug asserts, system signals, segfaults.
TEST(throw_int) {
try {
throw -1;
} catch (std::exception &e) {
std::cerr << "caught " << e.what() << std::endl;
} catch (...) {
std::cerr << "caught ..." << std::endl;
}
}
Throwing an integer isn't really recommended though. It's better to throw something that inherits from std::exception.
You might expect to see something like this as a last ditch effort for documenting failure, though. Some applications aren't required to be very robust. Internal tools might cost more than they are worth if you went through the paces of making them better than hacked together crap.
int main(int argc, char ** argv) {
try {
// ...
} catch (std::exception &e) {
std::cerr << "error occured: " << e.what() << std::endl;
return 1;
}
return 0;
}

Help with Try Catch

I'm using the GLUTesselator and every once in a while EndContour() fails so I did this:
try
{
PolygonTesselator.End_Contour();
}
catch (int e)
{
renderShape = false;
return;
}
Why would it still crash, it should perform the catch code right?
How could I fix this?
Thanks
Does PolygonTesselator.End_Contour(); crash or throws it an exception?
Note that a real "crash" (segfault, illegal instruction etc.) does not throw an exception in the sense of C++.
In these cases, the CPU triggers an interrupt - this is also sometimes called exception, but has nothing to do with an C++ exception.
In C++ you are running on a real CPU - and not in a virtual machine like in Java where every memory violation results in language execption like NullPointerException or ArrayOutOfBoundsException.
In C/C++ a CPU exception / interrupt / trap is handled by the operating system and forwarded to the process as "signal". You can trap the signal but usually this does not help for crashes (SIGSEG, SIGILL, SIGFPU, etcc.).
You're getting SEH exception, or Structured Exception Handling. These exceptions are thrown by Windows under an entirely different system since SEH predates C++, and can't be caught by a standard C++ catch block (MSVC does however provide SEH catching).
Alternatively, if you're on Unix, the kernel doesn't use C++ exceptions either. It uses signals. I don't pretend to understand signals, since I don't develop for Unix, but I'm very sure they're not C++ exceptions.
You've violated a hardware rule that you can't de-reference a NULL pointer. You'll get an OS-level error, by exception or signal. You can't catch these things in a C++ catch block just like that.
Edit: If you're using MSVC on Windows and have a recent compiler, you CAN enable /EHa, which allows you to catch Structured Exceptions as well as C++ exceptions. I wrote this code that functions as shown:
int main() {
std::string string = "lolcakes";
try {
Something s;
int i, j;
i = 0; j = 1;
std::string input;
std::cin >> input;
if (input == "Structured")
int x = j / i;
else
throw std::runtime_error("Amagad hai!");
}
catch(std::runtime_error& error) {
std::cout << "Caught a C++ exception!" << std::endl;
}
catch(...) {
std::cout << "Caught a structured exception!" << std::endl;
}
return main();
}
Structured Exceptions include Access Violations, your particular error.
Two things :
If you are under VC 6 or more recent, use __try{}__except(EXCEPTION_EXECUTE_HANDLER){} instead. It will catch the SE. try/catch only catches C++ exceptions
I've had a hard time with GLU, so I can tell you this : if you can set the normal, SET IT. But otherwise, it's true that it's quite solid.
Since all you want to do when the exception arrives is set 'renderShape' to false I'd recomment the following code:
try
{
PolygonTesselator.End_Contour();
}
catch (...) // takes any type of exception
{
renderShape = false;
return;
}
That said of course if you really can't fix the source to the exception itself!!
Why would it still crash, it should
perform the catch code right? How
could I fix this?
Most likely because you are not actually catching what is being thrown. Are you sure that PolygonTesselator.End_Contour(); throws an int?
If your program fails with the message error reading from location 0x000000000, then it is not failing because of an exception, but because of a segfault. You can use the segvcatch utility to convert segfaults into catchable exceptions. Check out their examples.
As mentioned, this is an SEH Exception.
If you are using Visual Studio, you can configure your project to catch SEH exceptions in your try/catch block.
Project Properties > C/C++ > Code
Generation > Enable C++ Exceptions >
Yes with SEH Exceptions

how to get message of catch-all exception [duplicate]

This question already has answers here:
C++ get description of an exception caught in catch(...) block
(6 answers)
Closed 6 years ago.
If I want to write useful info to a file whenever i caught a catch-all exception, how to do it?
try
{
//call dll from other company
}
catch(...)
{
//how to write info to file here???????
}
You can't get any information out of the ... catch block. That is why code usually handles exceptions like this:
try
{
// do stuff that may throw or fail
}
catch(const std::runtime_error& re)
{
// speciffic handling for runtime_error
std::cerr << "Runtime error: " << re.what() << std::endl;
}
catch(const std::exception& ex)
{
// speciffic handling for all exceptions extending std::exception, except
// std::runtime_error which is handled explicitly
std::cerr << "Error occurred: " << ex.what() << std::endl;
}
catch(...)
{
// catch any other errors (that we have no information about)
std::cerr << "Unknown failure occurred. Possible memory corruption" << std::endl;
}
A caught exception is accessible by the function std::current_exception(), which is defined in <exception>. This was introduced in C++11.
std::exception_ptr current_exception();
However, std::exception_ptr is an implementation-defined type, so you can't get to the details anyway. typeid(current_exception()).name() tells you exception_ptr, not the contained exception. So about the only thing you can do with it is std::rethrow_exception(). (This functions seems to be there to standardize catch-pass-and-rethrow across threads.)
There's no way to know anything about the specific exception in a catch-all handler. It's best if you can catch on a base class exception, such as std::exception, if at all possible.
You can't get any details. The whole point of catch(...) is to have such "I don't know what can happen, so catch whatever is thrown". You usually place catch(...) after catch'es for known exception types.
I think he wants to make it log that an error occurred, but doesn't specifically need the exact error (he would write his own error text in that case).
The link DumbCoder posted above has at tutorial that will help you get what you're trying to achieve.