I am reading literature on "C++ Exception Handling" (EH) from various resources. I have understood the concepts as well as the syntax. BUT On a larger scale I am confused .
We write code to execute it completely. It is expected that the written code will execute in known specific way(s). If some part of code throws exception and it is handled and the program continues execution. But from throw point to catch function some function(s) did not execute,normally they should have been, then how come the program can continue further as it is not completely executed.
I have come across statements that tells EH is used for error recovery.
But i need some concrete example to see what error recovery means / how it is done especially in C++ EH.
When an exception is thrown, execution does not continue from the point immediately after where the exception was thrown. Rather, execution is transferred back to the "nearest"1 catch block that can catch the type of exception that was thrown. After the code in that catch block executes, execution continues in whatever code comes after it, just like usual. That might (eventually) lead back to the code where the exception was thrown, but 1) doesn't necessarily, and 2) if it does, re-runs the code leading up to that point, so if the exception isn't thrown (for whatever reason) the following code can be expected to execute normally (presuming, of course, that the other code is exception safe, so nothing has gotten mucked up in the process).
It's difficult to find good examples of error handling using exceptions (or otherwise, TBH), largely for some of the same reasons for using EH to start with -- the code to handle the exception properly is often (usually?) quite specific to the application at hand. For some small utilities and such, it may just print out an error message and exit. For a server that needs to keep running regardless of what happens, it might write something to the log, then continue executing.
Here "nearest" has nothing to do with location in the source code -- it's based on execution. When code in a try block is executed, the corresponding catch block is set up stack-style. When an exception is thrown, the stack is unwound until it reaches a catch block that can handle the exception that was thrown.
Exceptions are safety nets, but they aren't meant to handle programmer errors (i.e. segfaults)
For example, let's say you're trying to read a file on disk that hasn't been written yet, but you know it will be at some point. Would you want to crash and burn the entire process? Probably not.
If you caught some sort of exception that indicated the file wasn't there yet, you could handle it appropriately by retrying at a later time, or logging some sort of a message.
Note EH = Exception handling
We do EH to make sure that we do not get run time abnormal behavior of program, which can be due to some unexpected input/data at any point of execution or data corruption in processing. It depends on developer how he handles exception(s) i.e show any error message or correct the data and continue.
for example
class PlayGame{
private:
/* variable */
public:
bool inputUserName() throw(){
**** if user do not enter name throw exception
}
void play(){
********
}
void end(){
****
}
};
void game() throw(){
PlayGame pg;
pg.inputUserName();
pg.play();
pg.end();
}
void main(){
/* one way of work */
try{
game()
}catch (exception& e){
cout<<"Error occour.. user name missing..\n";
}
/* second way can be */
try{
game();
}catch (exception& e){
cout<<"Please enter name first...\n";
game();
}
}
This is good example of understanding EH in c++
Maybe the concept of "strong exception safety" provides somewhat an answer to both of your questions. A function which is strongly exception safe will either complete regularily or, if throwing, leave the state of the program as it was before it was called.
Disregarding for the moment if that can be achieved, let's assume your code is composed of strongly exception safe functions:
Obviously execution can continue whenever an exception is caught. Just catch it at a point where there is an alternative route for execution. Ultimately just not executing the program at all. Of course you must admit failure to execute as a possibility. However, anything else would be perfection and somewhat unrealistic.
I recommend Herb Sutter's "Exceptional C++" books (see http://www.gotw.ca/publications/xc++s.htm) or his Guru-of-the-Week postings, e.g. http://www.gotw.ca/gotw/059.htm
In general "error recovery" here means rolling back any changes. This usually can only be achieved by doing everything tentatively, eg. on a copy, until success is ensured.
Above that, error recovery is an architectural issue of designing your program with lots of places, where alternative executions routes exist.
Related
There are a few SO posts about whether or not declaring main() using function-try-block syntax is valid syntax, and the general consensus seems to be that it's perfectly valid. This left me wondering... is there any reason (performance, style, thread synchronization, multithreading) why one wouldn't use this syntax for main() as a general rule to catch any unhandled exceptions anywhere more gracefully?
Obviously, ideally there won't be unhandled exceptions, but they happen and I think it'd be nice to provide something more informative than the OS-specific default handler. For example, in my case, I'd like to provide a support email address to the user so they can report the crash and have my program submit a log to my cloud-based crash log.
For example, in my case, I'd like to provide a support email address to the user
Well, how are you going to do that in a server with no user-facing interface?
Actually, how are you going to do that even in a process with user-facing components, if you have no way to tell in the catch block what state they're in?
And, for those processes where you can't show the user anything useful (or don't have any concept of a "user" in the first place), what would you do in your catch block that would be better than the default terminate?
As for
... more informative than the OS-specific default handler ...
many OS' default behaviour will be to save a complete snapshot of the process execution state, at the point the un-handled exception is thrown, to a file for debugging. As the developer, I can't think of many default behaviours that would be more informative.
Admittedly I'd prefer something more polished as the end user of a desktop app, but that's a pretty small subset of C++ programs.
You can easily convert
int main() try {
// The real code of main
}
catch (...)
{
}
to
int realMain()
{
// The real code of main
}
int main()
{
try
{
return realMain();
}
catch ( ... )
{
}
}
without losing functionality/behavior.
I am going to guess that whether you use the first version or the second version is a matter of coding practices of a team. From a compiler and run time standpoint, I don't see any semantic difference.
If you happened to have a variable that you want to access in your catch block, you would need the curly braces to provide visibility. But even that could be handled with nested try/catch...
why one wouldn't use this syntax for main() as a general rule to catch
any unhandled exceptions anywhere more gracefully?
compatibility with C.
Sometimes there is no way to handle unhandled exceptions more gracefully.
Obviously, ideally there won't be unhandled exceptions, but they
happen and I think it'd be nice to provide something more informative
than the OS-specific default handler. For example, in my case, I'd
like to provide a support email address to the user so they can report
the crash and have my program submit a log to my cloud-based crash
log.
If unexpected exception happens you can not be sure that it is possible to handle it correctly. What are you going to do if there is a network error exception in your example. And trying to send e-mail causes another exception? There can be other errors when you can not be sure that your data is not corrupted and you can not be sure that your program can run correctly after this error. So if you don't know what error happened it is better to allow your program to crash.
You can implement another "watcher" service that checks if process is running and if it has been crashed it can send e-mail to your users with the logs and core dumps.
If you catch the (otherwise) uncaught object, you won't be able to figure out how the execution reached the throw by inspecting the stack trace, because when exception handler is executed, the stack has already been unwound.
If you let the unexpected exception to be uncaught, you may be able to inspect the stack trace in the terminate handler - this is not guaranteed by the standard, but that's not a big deal since there is no standard way to inspect the stack trace either (in C++). You can either use platform specific API within the program, or an external debugger for the inspection.
So for example in your case, the advantage of not catching the exception would be that you can attach a stack trace to the log entry that you intend to submit.
Also, there are cases where an exception can not be handled by a catch block. For example, when you throw from a destructor that is being executed as a result of throwing an exception. So, to handle these "uncatchable" exceptions, you need a terminate handler anyway, so there is little advantage in duplicating the functionality in the case of uncaught exceptions.
As for the syntax that you use to catch the exception, there is no difference. The case where the function try block is different is a constructor, where it allows catching exceptions thrown by sub object constructors.
Is it possible to make a destructor catch exceptions and then re-throw them?
If so, how would I do that, since there isn't a clear place for a try statement?
Basically, I want to ideally do:
CMyObject::~CMyObject()
{
catch(...) // Catch without a try. Possible?
{
LogSomeInfo();
throw; // re-throw the same exception
}
// Normal Destructor operations
}
Background
I have a large, complex application that is throwing an unhandled exception somewhere.
I don't have easy access to main or the top level message-pump or anything similar, so there's no easy place to catch all unhandled exceptions.
I figure any unhandled exception has to pass through a bunch of destructors as the stack is unwound. So, I'm contemplating scattering a bunch of catch statements in destructors. Then at least I'd know what objects are in play when the exception is thrown. But I have no idea if this is possible, or advisable.
EDIT: You can use std::uncaught_exception to check if an exception is currently being thrown (i.e. if stack unwinding is in progress due to an exception). It is not possible to catch that exception or otherwise get access to it from your destructor. So if your logging doesn't need access to the exception itself, you can use
CMyObject::~CMyObject()
{
if(std::uncaught_exception()) {
LogSomeInfo(); // No access to exception.
}
// Normal Destructor operations
}
Note that this question was asked in 2013, meanwhile std::uncaught_exception was replaced with std::uncaught_exceptions (notice the additional s at the end) which returns an int. For a rationale, see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4152.pdf, so if you are using C++17, you should prefer the new version. The above paper also explains why the old std::uncaught_exception will not work as expected in some situations.
Another option might be std::set_terminate. This is useful if you want to have a method called when an exception is not caught and about to terminate the program. In the terminate handler, I usually print some information about the exception and a (demangled) backtrace of where it originates from to my log file before finally terminating the program. This is compiler and system specific, but a real helper as it saves a lot of time if you write server processes and often the log file is all you get from ops.
You can use std::uncaught_exception() which returns true if and only if there is an exception being processed. It has been available since C++98, and is superseded by std::current_exception which returns a std::exception_ptr.
However you must be careful not to throw another exception in an unguarded context, otherwise std::terminate will be caught. Example:
X::~X() {
if (std::uncaught_exception()) {
try {
LogSomeInfo();
// and do something else...
} catch(...) {}
}
}
A destructor cannot catch the exception that is causing the destruction of the instance.
You can only know if there is any "active exception" (see uncaught_exception) during the destruction (or, in C++17, how many of them there are there with uncaught_exceptions) but it's possible that the exception(s) are indeed going to be handled after that.
Dealing with exceptions is very hard, much harder than someone may think at a first sight and the reason is that exception safety doesn't scale by composition. This in my opinion means that is basically impossible to have non trivial stateful subsystems with strong exception safety (in case of an exception being thrown nothing happened to the internal state). This was discovered long ago (see 1994 Tom Cargill's "Exception handling: A False Sense of Security") but apparently is still ignored by large part of the C++ community.
The only reasonable way to handle exceptions I can think to is to have subsystems with clear well defined interfaces with thick "walls" (no side effect happening inside may escape), and that can be re-initialized to a well known state from scratch if needed when something goes wrong. This not trivial but can be done correctly to a reasonable extent.
In all other cases the global state of the system when an exception is caught is indefinite at best at the point of catch and there are in my opinion few use cases in which you can do anything in such a condition except dying immediately as loudly as possible instead of taking further actions without indeed knowing what is going on (dead programs tell no lie). Even keeping on calling destructors is somewhat questionable in my opinion.
Or you may try to be as functional as possible, but that's not an easy path either (at least for my brain) and it's also moving far away from reality (most computers are mutable objects with many billions of bits of mutable state: you can pretend this is not the case and they're instead mathematical functions with no state and with predictable output dependent on input... but in my opinion you're just deluding yourself).
I want to know, is it a good practice to place complete code inside a try block or I should place only the code which I feel it will cause a specific exception?
And should I catch basic Exception always
Code 1: complete code in try block
myFunction(){
try{
.........
Code with chance of OneException
.............
}catch(OneException e){
............
}catch(Exception e){
..............
}
}
Code 2: Only the Code with chance of Exception in try block
myFunction(){
.......
try{
Code with chance of OneException
}catch(OneException e){
............
}
............
}
Code 3:Should I catch Exception always
myFunction(){
.......
try{
Code chance of OneException
}catch(OneException e){
............
}catch(Exception e){
..............
}
........
}
Out of this (code1, code2 and code3) which one is the best?
I'm mainly concern with java and C++ coding
Generally speaking, you should only catch exceptions you're interested in and which you can handle. That is...catch an exception where you can do something s.t. the user doesn't perceive the problem or when it is explicitly necessary to tell the user about the problem.
For all other exceptions, let them pop up with all their details (stacktrace etc..) which you obviously log. Note, obviously this doesn't mean the user should also see that exception output but rather a generic error.
Told this, I assume that when you write "Code chance of OneException" you know how to handle OneException, but not Exception, right? So then...only handle OneException.
Always catch exactly what you have to and no more. No matter how much we try, we cannot make our code completely "idiot proof". If someone passes you something which will cause some random error, then it is their job to handle it. If our code handles someone else's exception that has far too much risk of being an unexpected side-effect.
As far as what code to place where: code before the line which could throw the Exception will be run either way, so it does not really make sense to have it inside the try block and before the code which throws. Code after the potential exception should be placed between try and catch if and only if it depends on the exception generating code. So, if your database connection call can fail, place all of the database queries inside the try block.
Limiting the "time" spent in a try...catch makes it easier to read and less prone to accidental catching. I can't tell you how many hours have been lost because someone decided to catch an Exception which should have propagated.
a) It is bad practice, to place complete code inside a try block.
a1) Beside of catching exceptions, a try-block is a documentation where an exception might happen. So place it close to the cause, you have in mind.
a2) In bad circumstances, you have a file for reading, and add later one for writing, but your exception (FileNotFoundException) was written only with the first in mind. A lean scope around the problematic places will help you, identifying further problems.
b) Don't catch basic Exception for completeness or to avoid multiple catch blocks. If you want to write to a file, many things can go wrong: Missing permission, illegal file name, no space left on device, ... . If you present the user a generic Message ("Couldn't write file " + name), he doesn't know what to do. Be as specific as possible, and you can inform him, "Only 20 MB left on device " + devicename + "We need another 8 MB (28 MB in total); please free some space and repeat or choose a different device!"). If you catch "Exception", chances are high, that you're thinking of some exception, but another one occurs, and isn't handled correctly, because the catch-block wasn't written with that possibility in mind.
The best chance to find this exception is, to let it pop up, or, to log it, if the logs are controlled on a regular basis.
It can be a difference between developing an application, which is simply used by end users, or by developing an API, which is used by other developers.
In an API, you often want to wrap an exception into an own exception, to make it easier for users of your api to handle it, and if you have an uniform way to handle exceptions. If your code can throw many exceptions, and would lead to ugly client code, where your customer would need to specify a bunch of exceptions over and over again, you often wrap the exceptions and rethrow them:
try {
...
}
catch {FileNotFoundException fnfe}
{
throw new MyApiException (fnfe);
}
catch {PermissionDeniedException pde}
{
throw new MyApiException (pde);
}
catch {IOException ioe}
{
throw new MyApiException (ioe);
}
That way, your client can decide, how to handle the exception, and will find the specific type of exception, if interested, inside your exception.
As Landei points out, in Java 7 there will be a simplified technique, to catch multiple exceptions, but not only such with a common superclass, see this link here
Wrap the code at the point where you really can handle the exception, and where you can handle the error. If you can't handle the error in the function, then do no wrap the code in try/catch block.
I don't know for java, but in c++ you should catch by const reference :
try
{
// code that can throw an exception
}
catch ( const SomeExceptionType & error )
{
// handle the error
}
C++ isn't Java or C# or... where you need catch (or finally) clauses to clean up after yourself. In C++, RAII does that. Consequently, I rarely ever write try/catch statements in C++, to the point where I consider it a code smell.
So, rather than contemplating which style of code you should use in conjunction with try/catch, you should ask yourself whether you need that try/catch at all.
I'm trying to understand error handling in C++.
I have read that using try, throw, catch is better style and less complicated than using if statements with return values. But I'm not sure I really understand how try, throw, catch works. I made a simple example below and it would be great to get feedback about any problems or bad style. My goal is to make a function out of the example that checks the results of another calculation.
Here are questions I have about try, throw, catch:
(1) Should the catch statement be included in my function? Or should it be somewhere else, like in main() or in the function where the initial calculation is done?
(2) Is it overkill to use try, catch, throw for something this simple (I would like to improve my style)?
(3) If there is an error, I would like to terminate the program. How would I do that? Or does "catch" mean that that is done automatically?
(4) I don't understand the use of cerr. Why not just use cout? Have I used cerr correctly here? Should I also have used it in the if/else statements?
Thanks a lot for any help.
Here's the example I made:
double calculated = 10.2; // from previous calculation
double tolerance = 0.3; // I can set this in this function
double valueWanted = 10.0; // from previous calculation
const int calcError = 5; // I picked this number randomly to use for indicating an error
try
{
if (fabs(fTargetValue - fCalculated) <= fTolerance)
cout << "Result is within range.";
else
cout << "Failed.";
throw calcError;
}
catch (const int calcError)
{
cerr << "The calculation failed.\n" << endl;
}
Well that's a lot of questions. I will try to give you some hints :
(1) Do not include the try-catch in your function. Throwing an exception is done to tell the outer world that something happened. If you can handle the problem in your function, do not throw at all ^^ A good error handling is generally to catch the error ASAP (in the caller) or in a general purpose handler far away like in main, to handle gracefully unhandled errors.
(2) As a rule of thumb, use exception for ... exceptional things. Errors are good candidate for exceptional things. An exception could be thrown for things like overflow or division by zero in a math library. You have to decide, but in general it is good to handle errors with exceptions.
(3) catch do not mean that your program will end. In fact it is the contrary. By catching an exception, you say that you will handle the problem ^^ If you want to terminate, a simple way in a simple program is to not catch exception, as the default behavior for uncaught exception is program termination ^^ Instead, you can explicitly terminate your program in some catch block.
(4) cerr is just like cout, but is a different file descriptor. It means that external programs can differentiate cerr from cout. It is used for error, but that's not really important but for external programs.
my2c
Ok, firstly your example will throw every time because you do not have scope braces after the else. Therefore, only cout << "Failed."; will be executed and throw calcError will be executed each time, regardless of whether the result was in range or not. Change this to:
else
{
cout << "Failed.";
throw calcError;
}
In the event that an exception is throw, the code will begin within the catch block you have defined, stating the calculation failed.
If the result was in range (throw is never called), code will begin executed directly after your catch block.
When you throw a type, that type arrives at the catch handler. This allows you to define catch handlers for different types. In this case, you are throwing (and catching) a const int. That's all good. Generally, we throw std::exception or a derivation of this. Your own exception classes can contain information pertinent to the error. In your case you could include a simple message that it was out of range, or indeed include the const int that failed.
The catch statement should be in the first function up from the one that throws (maybe in the function that throws) that can recover from the exception and allow the program to continue normally.
Yes, there's no point throwing really if you expect to be catching it. Also, your normal program flow shouldn't throw. As a rule of thumb, only throw for when you get into a situation you don't really expect should ever happen. Exceptions are called exceptions because they happen in exceptional circumstances. Often a good time to use exceptions is when interacting with the programs environment. You usually expect certain things to work, eg to be able to allocate memory, open a file, receive a complete data packet from a network device etc. All these cases should result in an exception being thrown. Also, if your program receives input, it should initially validate it. But, later on, during processing, if there's something wrong with the data that should already have been rejected by the validation, such as a divide by zero occurring because of strange input data, that would also be an exceptional situation. IF you rely on exceptions too much for when expected things happen, the flow and logic of your program can become overly difficult to reason about and the program maintenance gets unnecessarily hard.
If there is an error, just don't catch. If there's no catch, the exception will go all the way up to your main function, and will then go to the runtime from there which will terminate your program. And, for some O.S.s such as windows this will cause a minidump file to be created which you could use to debug your program with to find out what exception caused it to terminate.
cerr and cout just give you two ways of outputting information from your program. In cases where another program consumes the output of your program to do something, it will read cout and expect to understand it. This means if you want to write out errors or warning that the consuming program won't understand you have to write them to cerr so that you don't confuse the second program that's reading your programs normal cout output.
The C++ standard has a few exception classes that are all derivable from. I suggest you do that instead of throwing and catching PODs. It's not hard, either, and would improve (and specify the type of error) like so
class CalculationError : std::invalid_argument
{
public:
CalculationError(std::string const& msg)
: std::invalid_argument(msg)
{}
};
For a quick overview of the exception hierarchy go to http://www.richelbilderbeek.nl/CppExceptionHierarchy.htm
The problem is: when you throw a POD type, there is no attached message. The great part about throwing exceptions is the ability to write out a message about what might have gone wrong, and how to fix it. This is not possible when throwing an int.
There are three output streams in C++: log, cerr, and cout. Each of them are represented differently, which means that, when starting your program, you can use the command line to filter out each of these streams. This is great for debugging then, as you can filter by cerr and see if your program failed a test.
Example: my_program > out.txt 2> log.txt (cout goes to out.txt, the others to log.txt)
However, I would recommend not just cerring. Usually, the point of a catch is to reverse program state! If you, for example, tried to allocate a dynamic array, and that fails, the catch would be responsible for destructing the array again before rethrowing. Otherwise, you would have a whole bunch of things like memory leaks and whatnot.
What's also important to note is that, once caught, the exception is "swallowed". If you cannot or do not want to deal with the error here, it is best to write
catch(/* Error to be caught */)
{
throw; // Rethrows original exception, propagating it upwards
}
If you want some good literature about this, Herb Sutter wrote a book called Exceptional C++ and it covers exception safety in a practical and enlightening way (imo). It's definitely worth checking out if you want to know when and why you need to throw exceptions.
Hope this helps!
Did not you forget a block around the else case
try
{
if (fabs(fTargetValue - fCalculated) <= fTolerance)
cout << "Result is within range.";
else {
cout << "Failed.";
throw calcError;
}
}
There are lots of good answers here for your questions. I was just reading about cerr and I would like to share what I was reading here. The source is "C++ Basic Structures: Vectors, Pointers, Strings, and Files" course in Coursera platform.
Here is the quote:
"When printing error messages, cerr is preferred over cout. cerr is not bufferred, which means it is not stored in memory to be printed later on. It just gets printed immediately. Therefore, as a rule of thumb, important data and variables should be printed with cout while error messages should be printed with cerr."
Also:
"cerr is an unbuffered output stream. This means that the output is immediately printed and not stored for later. This makes cerr more suitable for use with error messages where its storage is not important.
On the other hand, cout is buffered, meaning its output is temporary stored so that the system can retrieve it later for quicker access. cout is more suitable for important data and variables that are used throughout the program."
Each time I have seen the catch all statement:
try
{
// some code
}
catch (...)
{
}
it has always been an abuse.
The arguments against using cache all clauses are obvious. It will catch anything including OS generated exceptions such as access violations.
Since the exception handler can't know what it's dealing with, in most cases the exceptions will manifest as obscure log messages or some incoherent message box.
So catch(...) seems inherently evil.
But it is still implemented in C++ and other languages (Java, C#) implements similar mechanisms. So is there some cases when its usage is justified?
(1) It's not true that the statement will catch OS exceptions. Your use of the term "Access Violation" betrays a Windows background; it was true for older MSVC++ versions.
(2) Regardsless, the catch-all behavior is useful for threads with specific purposes. Catching the failure allows the thread to report it failed. Without it, the other parts of the program need to deal with the possibility of a thread just disappearing. It also allows you to log which thread failed, and the arguments used to start the thread.
The case where it's justified in general is when you log the exception (or do something similar) or do some cleanup, and then immediately rethrow.
In C++ in particular, logging in a catch(...) block is pretty pointless since you don't have any way to obtain the exception, and cleanup is pointless because you should be using RAII for that. Using it in destructors seems to be about the only legitimate case.
the arguments against using cache all clauses are obvious , it will catch anything including OS generated exceptions such as access violation. since the exception handler can't know what its dealing with, in most cases the exceptions will manifest as obscure log message or some incoherent message box.
And if those same exceptions aren't caught you get... an incoherent message box.
catch(...) lets me at least present my own message box (and invoke custom logging, save a crash dump, etc.).
I think there are also reasonable uses of catch(...) in destructors. Destructors can't throw--well, I mean, they can throw, but if a destructor throws during stack unwinding due to an in-progress exception the program terminates, so they should not ever allow exceptions to escape. It is in general better to allow the first exception to continue to be unwound than to terminate the program.
Another situation is in a worker thread that can run arbitrary functions; generally you don't want an unceremonious crash if the task throws an exception. A catch(...) in the worker thread provides the opportunity for semi-orderly clean-up and shutdown.
In addition to what other posters have already said, I'd like to mention one nice point from the C++ Standard:
If no matching handler is found in a
program, the function std::terminate()
is called; whether or not the stack is
unwound before this call to
std::terminate() is
implementation-deļ¬ned.
(15.3/9)
This means that main() and every thread function must be wrapped in a catch-all handler; otherwise, one can't even be sure that destructors for automatic objects will be called if an uncaught exception is thrown.
try {...} catch (...) is needed around body of callback function which is called from code
that doesn't understand C++ exceptions (usually C library).
Otherwise, if some C++ library you use throws an exception that doesn't derive from
std::exception, it will probably cause calling code to crash or corrupt its internal state.
Instead you should catch this exception and either finish program immediately or
return some error code (meaning "we are doomed and I don't know why", but it's still better
then letting C++ exception to pass through).
Around thread procedure. Mostly because of the same reason as 1.
And because otherwise thread failure would pass unnoticed.
catch(...) has been useful for me in two circumstances, both of which are unjustified (I can't even remember the second)
The first is my overall application safety. While throwing exceptions that don't derive from std::exception is a No-No, I have one just in case in my main() function:
int execute(void); // real program lies here
int main(void)
{
try
{
return execute();
}
catch(const std::exception& e)
{
// or similar
std::cerr << "Unhandled exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(...)
{
std::cerr << "Unknown exception!" << std::endl;
return EXIT_FAILURE;
}
}
Now, it's only there "just in case", and it's not really justified. There should be no reason to ever enter that catch clause, as that would mean somebody has done a Bad Thing. Observe how useless the statement really is; "Something bad happened, no clue what!" It's only a step above just crashing in the first place.
The second use might be in destructors or some other function that needs to do manual management before letting the exception propagate. That's not really a justification either, as things should clean themselves up safely with RAII. But I may have used it once or twice for some reason I can't recall, and I can't see a reason to ever do so again.
catch (...) allows you to write code in which you can legitimately claim a guarantee that your code will not crash even when you are not in long term complete control of the submodules your code depends on. Your claim is tantamount to claiming that this semantic cannot be used except as a means of abuse. Maybe so, but military specifications may differ from you on this issue.
catch(...) is necessary in the absence of the finally clause as found in other languages:
try {
...
} catch(...) {
cleanup...
throw;
}
The alternative - making stack objects to 'own' everything - is often much more code and less readable and maintainable. The platform API is often C, and does not come with it conveniently bundled.
It is also useful around plugin code that you do not control or simply do not trust from a stability perspective. It won't stop them crashing, but it might keep things a little saner.
Finally, there are times when you really do not care about the outcome of something.