开发者

How can I catch runtime error in C++

By referring to C++ catching all exceptions

try {
    int i = 0;
    int j = 0/i; /* Division by  0 */
    int *k = 0;
    std::cout << *k &l开发者_开发技巧t;< 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?


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.


/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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜