Reputation: 42828
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?
Upvotes: 2
Views: 5280
Reputation: 35490
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.
Upvotes: 1
Reputation: 58715
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.
Upvotes: 0
Reputation: 11991
/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.
Upvotes: 3
Reputation: 258478
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.
Upvotes: 2
Reputation: 355307
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.
Upvotes: 7