C++: Should I catch all exceptions or let the program crash? - c++

I have a Windows service written in (Visual) C++ with a very detail logging functionality that has often helped me find the cause of errors customers are sometimes experiencing. Basically I check every return value and log what is going on and where errors are coming from.
Ideally, I would like to have the same level of detailed visibility into exceptions (like array out of range, division by zero, and so on). In other words: I want to know exactly where an exception is coming from. For reasons of readability and practicality I do not want to wrap every few lines of code into separate try/catch blocks.
What I have today is one general catch-all that catches everything and logs an error before shutting down the program. This is good from the user's point of view - clean shutdown instead of app crash - but bad for me because I only get a generic message from the exception (e.g. "array out of range") but have no idea where that is coming from.
Wouldn't it be better to remove the catch-all and let the program crash instead? I could direct the customer to have Windows create an application crash dump (as described here). With the dump file WinDbg would point me exactly to the position in the code where the exception was thrown.

You can register a custom, vectored exception handler by calling AddVectoredExceptionHandler .
This will get called whenever an exception gets thrown, and in it you can generate a stack trace that you can then save off for logging purposes.
Writing the code to do this is not completely trivial but not rocket surgery either.
I've never personally done it in C++, but I would be surprised if there weren't ready-built libraries that do this available somewhere, if you don't have the time or inclination to do it on your own.

You can throw exceptions with description where the error occurred and why:
throw std::string("could not open this file");
If you do not want to write different descriptions for every possible error you can use standard macros __FILE__ and __LINE__:
#define _MyError std::string("error in " __FILE__ + std::to_string(__LINE__))
// ...
throw _MyError;
If source file name and line of the error is not enough and you need more information, for example stack trace or memory values, your program can generate a debug report. Google Breakpad is a C++ library that allows you to do that in a portable way. Class wxDebugReport from wxWidgets library is an alternative. On Windows the debug reports may include a minidump file that can be loaded in Visual Studio and allows you to analyse the error in a way similar to debugging.

Wouldn't it be better to remove the catch-all and let the program
crash instead?
You can catch-all and
Write a (more personal) message about the fatal error that occurred, forcing the application to be closed. Do not let the program continue: you don't know what happened, where. Continuing might cause damage to the user's data, follow up errors, etc.
Tell the user to contact you with specifics as to what they did and what happened.
Tell the user to include the log file your application has generated.
If you don't do something like this, then you might just as well remove the catch-all.
For reasons of readability and practicality I do not want to wrap
every few lines of code into separate try/catch blocks.
And yet if you want your program to be able to recover, this is exactly what you have to do. What you could do is
Tell the user what happened, perhaps what was wrong with the input that may have caused it. Don't make it sound technical.
Save any data the user has entered so their work is not completely lost
You know at which step the failure happened. Undo that step, i.e. throw away objects / data, and go back to the point before the exception.
Restore data the user had entered from the second point so they don't need to repeat actions all over again.
The point being that your program can return to a valid state.

Related

When can the problem actually be fixed by catching an exception?

Here's the thing. There's something I don't quite understand about exceptions, and to me they seem like a construct that almost works, but can't be used cleanly.
I have a simple question. When has catching an exception been a useful or necessary component of solving the root cause of the problem? I.e. when have you been able to write code that fixes a problem signaled through an exception? I am looking for factual data, or experience you have had.
Here's what I mean. A normal program does work. If some piece of work can't be completed for reason X, the function responsible for doing the work throws an exception. But who catches the exception? As I see it, there are three reasons you might want to catch an exception:
You catch it because you want to change its type and rethrow it. (This happens when you translate mechanical exception, such as std::out_of_range, to business exceptions, such as could_not_complete_transaction)
You catch it because you want to log it, or let the user know about the problem, before aborting.
You catch it because you actually know how to solve the problem.
It is point 3 that I'm skeptical about. I have never actually caught an exception knowing what to do to solve it. When you get a std::out_of_memory, what are you supposed to do with it? It's not like you can barter the operating system to get more memory. That's just not something you can fix. And it's not just std::out_of_memory, there are also business class exceptions that suffer from this. Think about a potential connection_error exception: what can you do to fix this except wait and retry later and hope it fixes itself?
Now, to be fair, I do know of one case in which code does catch an exception and tries to fix the problem. I know that there are certain Win32 SEH handlers that catch a Stack Overflow exception and try to fix the problem by enlarging the size of the thread stack if it's possible. However, this works because SEH has try-resume semantics, which C++ exceptions don't have (you can't resume at the point the exception occurred).
The main part of the question is over. However, there's also another problem I have with exceptions that, to me, seems exactly the reason why you don't have catch clauses that fix the problem: the code that catches the exception necessarily has to be coupled with the code that throws it. Because, in order to fix the problem, it must have domain specific knowledge about what the problem cause is. But when some library documents that "if this function fails, an internal_error exception will be thrown", how am I supposed to be able to fix the problem when I don't know how the library works internally?
PS: Please note that this is not a "exceptions vs. error codes" kind of question; I am well aware that error codes suck as an error handling mechanism. They actually suffer from the same problem I have explained for exceptions.
I think your problem is that you equate "solve the problem" with "make the program keep going correctly". That is the wrong way to think of exceptions, or error handling in general.
Error handling code of any kind should not be something that is internally fixable by the program. That is, error handling logic (like catching exceptions) should not be entered because of programming mistakes.
If the user gives you a non-existent filename, that's not a programming mistake; that's a user-error. You cannot "fix" that without going back to the user and getting an existing file. But exceptions do allow you to undo what you were trying to do, restore the program to a valid state, and then communicate what happened to the user.
An invalid_connection is similarly not a programming mistake. Unlike the above, it's not necessarily a user error either. It's something that's expected to be able to happen, and different programs will handle it in different ways. Some will want to try again. Others will want to halt and let the user know.
The point is, because there is no one means to handle this condition, it cannot be done by the library. The error must be given to the caller of the library to figure out what to do.
If you have a function that parses integers, and you are given text that doesn't conform to an integer, it's not that function's job to figure out what to do next. The caller needs to be notified that the string they provided is malformed and that something ought to be done.
The caller needs to handle the error.
You don't abort most programs because a file that was supposed to contain integers didn't contain integers. But your parsing function does need to communicate this fact to the caller, and the caller does need to deal with that possibility.
That's what "catching exceptions" is for.
Now, unexpected environmental conditions like OOM are a different story. This is not usually external code's fault, but it's also not usually a programming error. And if it is a programming error (ie: memory leak), it's not one you can deal with in most cases. P0709 has an entire section on the ability (or lack thereof) of programs to be able to generally respond to OOM. The result is that, even when programs are coded defensively against OOM exceptions, they're usually still broken when they run out of memory.
Especially when dealing with OS's that don't commit pages to memory until you actually use them.
Here is my take,
There are more reasons to catch exceptions, for example, if it is a critical application, such as ones found in power substations etc. and an exception is caught to which there is no known system recovery or solution, you may want to have a controlled shutdown, protect certain modules, protect connected embedded systems etc. instead of just letting the system crash on its own. The latter could be disastrous...
I.e. when have you been able to write code that fixes a problem signaled through an exception?
When you get a std::out_of_memory, what are you supposed to do with it? It's not like you can barter the operating system to get more memory.
Actually I feel like that was my primary coding style for a while. An example: a system I worked on did not have a huge amount of memory and the system was dedicated, so, it was only my app and nothing else. Whenever I had an out_of_memory type of exception, I'd just kill the older process and open the one with the higher priority. Of course I'd wait for the kill to happen in a controlled fashion.
Think about a potential connection_error exception: what can you do to fix this except wait and retry later and hope it fixes itself?
I'd try to connect through another medium such as bluetooth, fiber, bus etc. Normally of course there would be a primary medium of contact, and the others wouldn't be called unless there is an exception.
But when some library documents that "if this function fails, an internal_error exception will be thrown", how am I supposed to be able to fix the problem when I don't know how the library works internally?
Most often an exception in a dedicated library has different consequences in your system than its own. You may not need to read the library and its internal workings to fix the problem. You just need to study its effect on your software and handle that situation. That's probably the easiest solution. And that is a lot easier to do if the library raises a known exception instead of just crashing or giving gibberish answers.
One obvious thing that came to mind was socket connections.
You try and connect to Server A and the program finds that it can't do that
Try connecting to Server B
The other examples regarding user input are equally as valid if not more so.
I admit that seeing something along the lines of
try
{
connectToServerA();
}
catch(cantConnectToServer)
{
connectToServerB();
}
would look like a bit of a weird pattern to see in real world code. It might make sense if the function takes an address and we iterate through a list of potential addresses.
Broadly speaking I agree with you often all you want to do is log the error and terminate - but some systems, which have to be robust and "always on" shouldn't just terminate if they encounter a problem.
Webservers are one obvious example. You don't just terminate because one users connection faulters, because that would drop the session for all the other connected users. There might be parts of code where raising an exception is the simplest way to deal with such a failure however.

How to wrap my C code in C++ exception handling?

I have an old C based project, which I would like to port from an Atmel processor to Raspberry Pi.
At the time that it was written, C++ was not an option, and it would be too much effort, almost a rewrite, to convert it all to C++.
Some problems/crashes can't be (easily) caught by C, so sometimes my program will just die & I would like to send a last chance cry for help before expiring. No attempt at recovery and I can even live without details of the error, just so long as I get a message telling me to visit the equipment
Long story short, I think that I could have better error detection if I had exception handling.
I am thinking of using exception handling as chance of alerting me to go to the device and fetch the complete error log, reset the hardware etc. C won't always give me that last gasp chance to do something, if my code goes bang
Since I don't want to do a total C++ rewrite, would it be enough just to wrap main() in try / catch?
Is that technically enough, or do I need to do more?
Other than more detailed error reporting, is there anything to gain by wrapping every (major) function in it's own try / catch?
Other than more detailed error reporting, is there anything to gain by wrapping every (major) function in it's own try / catch?
Firstly, only catch exceptions where you are in a position to alter the behaviour of the program in response to them (unless you're simply looking to add more contextual information via std::throw_with_nested())
Secondly, a c program will not exhibit RAII, so throwing exceptions in this circumstance is likely to leak resources unless you wrap all your handle and memory allocation in smart pointers or RAII-enabled handle classes.
You should do that before you consider adding exception handling.
If the program is likely to be actively maintained into the future, there is probably mileage in doing this. If not, probably better to leave sleeping dogs lie.

Why is the throw location not in the backtrace / callstack?

I am attempting to make post-mortem life a little easier for a very large and cross-platform project that makes use of many 3rd party libraries. On Linux, I use backtrace() to dump the backtrace/callstack to console. On Windows, I use EXCEPTION_POINTERS to create a minidump and that StalkWalker class to dump the callstack to console. Now, with all the platform-specific signal handlers registered and SEH enabled on Windows, I catch and report a lot of helpful information, most importantly, the file and line number of where the bad thing happened. However, in the callstack, I have noticed that I never actually get the location of any throw statements, only where it was caught, i.e. a catch block. As you can imagine, if your try-catch encompasses a gigantic amount of code, where the exception was caught is not terribly helpful. So, why is that?
And now for the obvious followup question: How do I get the location of throw statements into my callstack console dumps?
I will stop anyone who tries to tell me to change all the throw statements to custom exceptions with __FILE__ and __LINE__ macros right here. Please refer back to my opening sentence. As such, present uses of throw will not be changed.

Can I get a stack trace for un-handled (Objective) C++ exceptions?

I'm developing an iOS application that has recently grown a large C++ base. C++ is not my forte, and I'm getting frustrated by exceptions. What I'm looking for is a way to get a stack track to the site of an (un-handled) exception throw. I'll say that the "un-handled" qualifier is optional; I would settle for breaking on any exception throw as a last resort, though un-handled exceptions are ideal.
What I currently get is useless. Assuming I don't have any appropriate exception handlers higher up the callstack, and I do something like
std::vector<int> my_vector;
my_vector.at(40) = 2; // Throws std::out_of_range
The app will break in main() and I'll get a log message saying "terminate called throwing an exception." Not helpful.
Putting generic try/catch blocks higher up the callstack doesn't help either, because the callstack is unwound during exception handling up to the point of the catch block, leaving me ignorant to actual origin of the exception. This also applies to providing my own terminate_handler. Asserts are more useful, but they require me to anticipate error conditions to some extent, which I cannot always do. I would still like the debugger to be able to step in even if an unexpected exception makes it past my pre-emptive assert()s.
What I want to avoid is having to wrap every call that might possibly throw an exception in a try/catch block just to get the stack trace to the error. At runtime, I'm really not interested in catching these exceptions. When they occur, it means there's a fatal flaw in the program execution, and there's no way it can continue normally. I just want to be notified so I can determine the cause and mend the issue so it won't happen again.
In Objective C, I can put a symbolic breakpoint on objc_exception_throw, and any time I screw something up I'll immediately break execution and be presented with a nice stack trace so I know where the issue is. Very helpful.
I realize this behavior is really only useful because of a philosophical difference in exception handling between the two languages. Objective C exceptions are intended only to signify unrecoverable errors. The task of routine error handling is accomplished via error return codes. This means that any Objective C exception is a great candidate for a breakpoint to the developer.
C++ seems to have a different use for Exceptions. They're used to handle both fatal errors and routine errors (at least in the 3rd party libs I'm using). This means I might not actually want to break on every exception that's thrown in C++, but I would still find the ability useful if I can't break only on un-handled exceptions.
You can quickly establish a break on all C++ throw conditions in Xcode:
cmd+6
"+" button -> Add Exception Breakpoint
C++ -> std::out_of_range
On Throw
Update
If you have a lot of them tho filter out, you may prefer to:
Create a Symbolic Breakpoint
Symbol = __cxa_throw (may vary by std library)
Action > Debugger Command = bt
Automatically continue after eval = On
The bt command logs the backtrace. Configured this way, it will automatically continue.
So, this will just log the backtrace of every thrown exception - when your program terminates due to an unhandled exception, the clues will be among the final logged backtraces (often the last, unless the library rethrows).
In the app I get to debug with many c++ exceptions, I leave the "Catch C++ Exceptions on Throw" off until I get to the point in the app where it will throw the exception, then I turn that option on and usually the next exception that is thrown is what I'm looking for. This will break a few levels deeper than where the error is, but the stack is intact so you can figure out what is going on.
Check PLCrashReporter. We use it with our application (which relies heavily on C++) and it produces stack traces even for the C++ code.
The only problem you might have is when using assembly routines which were not written natively for iOS (Apple's compiler is using R7 to hold the stack frame for tracing back symbols which is not according to official ARM EBI)

run-time error and program crash

How can I specify a separate function which will be called automatically at Run-Time error to prevent program crash?
Best thing as mentioned already is to identify the area where the crash ic occuring and then fix the piece of code. This is the idealistic approach.
In case you are unable to find that out another alternative is to do structured exception handling in the areas where you suspect crashes to occur. Once the crash occurs you capture what ever data you want and process it. Meanwhile you can change the settings in windows service manager to restart your application whenever it crashes. Hope this answers your question.
Also in case you are looking for methods to capture the crash and analyse debugdiag and windbg are some of the standard tools that people use to take the crash dumps.
If your in Windows you need to write your own custom runtime check handler. Use:
_RTC_SetErrorFunc
to install your custom function in place of
_CrtDbgReport.
Here is a good article on how to do it:
http://msdn.microsoft.com/en-us/library/40ky6s47(VS.71).aspx
If by run-time error you mean an unhandled exception, don't do it. If an unhanded exception propagates through your code, you want your app to crash. Maybe create a dumpfile on the way down, sure. But the last thing you want to do is catch the exception, do nothing, and continue running as if nothing had happened in the first place.
When an exception is generated, whatever caused the problem could have had other effects. Like blowing the stack or corrupting the heap. If you were to silently ignore these exceptions and continue running anyway, your app might run for a while and seem OK, but something underneath is unstable. Memory could be corrupt, resources might not be available, who knows. You will eventually crash. Bu ignoring unhandled exceptions and running anyway, all you do is delay the inevitable, and make it that much more difficult to diagnose the real problem, because when you do crash, the stack will be in a totally different and probably unrelated place from what caused the initial problem.