Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42828

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

Answers (5)

aJ.
aJ.

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

wilhelmtell
wilhelmtell

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

Terry Mahaffey
Terry Mahaffey

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

Mark Rushakoff
Mark Rushakoff

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

James McNellis
James McNellis

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

Related Questions