Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to catch exceptions in the main(...)?

I found some code in a project which looks like that :

int main(int argc, char *argv[])
{
  // some stuff

 try {
  theApp.Run();
 } catch (std::exception& exc) {
  cerr << exc.what() << std::endl;
  exit(EXIT_FAILURE);
 }
 return (EXIT_SUCCESS);
}

I don't understand why the exceptions are being catched. If they weren't, the application would simply exit and the exception would be printed.

Do you see any good reason to catch exceptions here ?


EDIT : I agree that it is good to print the exception error. However, wouldn't it be better to rethrow the exception ? I have the feeling that we are swallowing it here...

like image 932
Barth Avatar asked Dec 15 '08 12:12

Barth


2 Answers

If an exception is uncaught, then the standard does not define whether the stack is unwound. So on some platforms destructors will be called, and on others the program will terminate immediately. Catching at the top level ensures that destructors are always called.

So, if you aren't running under the debugger, it's probably wise to catch everything: (...) as well as std::exception. Then your application code can clean up with RAII even on a fatal exception. In many such cases you don't actually need to clean up, since the OS will do it for you. But for instance you might prefer to disconnect cleanly from remote services where possible, and there might be resources external to the process, such as named pipes/mutexes, that you'd prefer to destroy rather than leaking.

Rethrowing the exception in main seems to me of limited use, since you've already lost the context in which it was originally thrown. I suppose that trapping an uncaught exception in the debugger is noisier than just logging the fault to std::cerr, so rethrowing would be the smart move if there's a chance of missing the logging.

If you want the debugger to trap unexpected conditions in debug mode, which in release mode throw an exception that eventually results in an exit, then there are other ways to do that than leaving the exception uncaught so that the debugger sees it. For example, you could use assert macros. Of course, that doesn't help with unexpected and unpredictable conditions, like hardware exceptions if you're using SEH on .NET.

like image 84
Steve Jessop Avatar answered Nov 01 '22 07:11

Steve Jessop


Why do you say that the exception would be printed? This is not the typical behavior of the C++ runtime. At best, you can expect that its type gets printed.

In addition, this program leaves a "failure" status, whereas an exception might cause a termination-through-abort status (i.e. with a signal indicated in the exit code).

like image 36
Martin v. Löwis Avatar answered Nov 01 '22 07:11

Martin v. Löwis