-1

Possible Duplicate:
How to prevent crash in C++

typedef struct {
    int val;
} valStruct;

main()
{
    try {
        valStruct *s = NULL;
        int v = s->val;       // bad 
    }
    catch (...) {}
}

Fairly new to MacOS. Running under the debugger I get a EXC_BAD_ACCESS break. Not too hard to guess that it means a bad memory access occurred, but I do not get a C++ exception and in the code above my catch will not be invoked.

This seems to be a bad thing, pretty much rendering C++ exception handling useless. Unless this is just a debug thing. If I run in release mode, or change settings, will this be handled as an exception?

Community
  • 1
  • 1
Ted P
  • 95
  • 1
  • 10
  • 1
    [The exact same thing was asked about an hour ago.](http://stackoverflow.com/questions/12978234/how-to-prevent-crash-in-c/12978275#12978275) –  Oct 19 '12 at 17:34
  • OK I need to get better at searching stackoverflow. – Ted P Oct 22 '12 at 22:36

1 Answers1

5

Shortly: no. A segmentation fault (and some of the other common programming mistakes) are not "high-level" enough to be caught by C++ exception handlers, so the program will just crash. The solution: don't rely on C++ exceptions magically saving you from thinking and writing good code. They're not for that. You should really check for pointers being non-NULL before dereferencing them and things like that.

  • Who said anything about magically saving? I think the issue is more of providing some sort of consistent experience when a failure occurs. But answer accepted. – Ted P Oct 22 '12 at 22:38