0

I have a try block which currently catches all exceptions:

try
{
    // do some work
}
catch (std::exception &ex)
{
    // log ex
}

However, I do not want to catch access violations. Can I specify that as an exception (so to speak) of my handler? Or should I catch it first and rethrow it?

Justin R.
  • 23,435
  • 23
  • 108
  • 157
  • 2
    Note that your `catch` statement does not catch all exceptions. Only those who derive from `std::exception`. In C++, exceptions are not required to derive from `std::exception` or even be instances of a class; you can `throw` an `int`, for example. – Nikos C. Jan 09 '14 at 18:28

1 Answers1

10

You are already not catching access violations and you never could. Access violations are not C++ exceptions. They are "exceptions" of a different kind — that raised by your operating system. I prefer not to call them "exceptions" at all, in fact.

Linux and Linux-like operating systems simply terminate a process (using a signal) that performs an access violation.

Windows instead uses something called "structured exceptions" which you can potentially catch and possibly ignore using language extensions in Visual Studio. We're venturing off-topic now, but you could read up about those. I still wouldn't recommend their use, mind you. Once you have an access violation I'd personally be content to say "all bets are off", and "we have some debugging to do".

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    Although, if you use Visual C++, the language extensions make SEH look a whole lot like exceptions, from what I understand. SEH exceptions are still not C++ exceptions, of course. – John Chadwick Jan 09 '14 at 18:20
  • You can, however, trap access violations on *nix by setting up a handler for the `SIGSEGV` signal. It's fair to say that a program that triggers that signal is probably broken anyway, but this is a good way to "catch" such violations and produce logging information. – greyfade Jan 09 '14 at 18:41
  • @greyfade: Technically, yeah, but [blimey you really shouldn't](https://www.securecoding.cert.org/confluence/display/seccode/SIG35-C.+Do+not+return+from+a+computational+exception+signal+handler)! And certainly this is not supported within the scope of the language. – Lightness Races in Orbit Jan 09 '14 at 18:43