2

By referring to C++ catching all exceptions

try {
    int i = 0;
    int j = 0/i; /* Division by  0 */
    int *k = 0;
    std::cout << *k << std::endl;  /* De-reference invalid memory location. */
}
catch (...) {
    std::cout << "Opps!" << std::endl;
}

The above run-time error are unable to be detected. Or, am I having wrong expectation on C++ exception handling feature?

Community
  • 1
  • 1
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

5 Answers5

7

If you dereference a pointer that doesn't point to an object, you don't get an exception, you get undefined behavior. Anything can happen.

Usually, if you dereference a null pointer, as you do in your example, the program will crash.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
3

/EHa is the magic compiler switch to make Visual Studio treat SEH exceptions as C++ exceptions. Then you can "catch" access violation and divide by zero exceptions.

This is generally not advised.

Terry Mahaffey
  • 11,775
  • 1
  • 35
  • 44
2

When you run this program (at least on my system when I run it), you aren't throwing C++ exceptions; you're actually segfaulting the standard C library. A segmentation fault in a library is not a C++ exception, so the C++ runtime has nothing to catch.

Contrasting this program with, say, an equivalent program in C# or Java, the difference is that their respective runtimes will treat these errors runtime exceptions and will not segmentation fault any external libraries.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
1

These are not C++ exceptions. These are OS exceptions. If you are using Windows, you can enable asynchronous exception model (/EHa flag) and catch Win32 exceptions.

aJ.
  • 34,624
  • 22
  • 86
  • 128
0

The runtime environment C++ gives you is very thin. In most cases it will do what you program it to do and won't do what you don't program it to do. You can write a wrapper for your pointers which will do the check when you dereference a null pointer. In fact, boost::shared_ptr<> does assert for not equalling null when you dereference it, so you get a similar performance to that of native pointers while giving the extra information you're after while debugging.

wilhelmtell
  • 57,473
  • 20
  • 96
  • 131