Mike Pateras
Mike Pateras

Reputation: 15015

How do I catch a C++ exception?

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?

Upvotes: 1

Views: 1194

Answers (5)

Gerald
Gerald

Reputation: 23499

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.

Upvotes: 0

plan9assembler
plan9assembler

Reputation: 2984

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

SEH and C++ Exceptions - catch all in one

Upvotes: 0

Alok Save
Alok Save

Reputation: 206636

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.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283893

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.

Upvotes: 1

user229044
user229044

Reputation: 239521

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.

Upvotes: 9

Related Questions