views:

97

answers:

5

In my C++ app, I'm making a call to System() that crashes the app sometimes (it's a service). I'd like to catch the exception that is thrown and log it. I don't know what exactly to catch, though, and I can't even do a blanket catch:

try
{
   system(myCommand);
}
catch (...)
{
   Log("Error!"); // this is a custom log method
}

That doesn't log anything. Shouldn't that catch every type of exception? And more importantly, how do I know what the System() method will throw so that I know what to catch?

+9  A: 

If catch(...) isn't catching an exception, an exception isn't being thrown. Not all errors raise exceptions. system is a hold-over from the days of C, and definitely doesn't raise any exceptions.

meagar
Is there a way that I can find out what went wrong with the call, then?
Mike Pateras
You can check the return value of `system`: "In many systems, 0 is used to indicate that the command was successfully executed and other values to indicate some sort of error."
meagar
But the app has crashed by that point.
Mike Pateras
+1  A: 

What functions does "Log" use? Depending on the failure you are experiencing, it could interfere with your logging function. Generally crash logging should be done from a separate process.

Ben Voigt
It just writes to a file via ofstream and the << operator.
Mike Pateras
+2  A: 

You should check the documentation of System() call to check if it defines an exception specification aka what exceptions it can throw. But seems since (...) catch all seems not working for you, mostly System() is not throwing any exceptions at all. You can check in to trace logs or debugger logs to see what goes wrong during a System() call.

Als
What do you mean by trace logs and debugger logs?
Mike Pateras
@Mike: Usually every piece of software provisions for logs to get information about important events during the lifetime. You can find these trace logs under output window when you run the software. Just read one of your comments that you dont have a debugger and output window, without these its difficult to track down the problem...One can only speculate if cant actually debug or see logs.
Als
A: 

try/catch only catches C++ exceptions, it does not catch all exceptions (i.e. SEH-type exceptions). If you're sure that the service is being crashed by that call, and this is on Windows, you might want to try using Structured Exception Handling instead.

Gerald
A: 

you can catch SEH and c++ exceptions both, HTH.

SEH and C++ Exceptions - catch all in one

plan9assembler