Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch runtime error in C++

Tags:

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?

like image 698
Cheok Yan Cheng Avatar asked Aug 12 '26 23:08

Cheok Yan Cheng


2 Answers

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.

like image 177
James McNellis Avatar answered Aug 15 '26 01:08

James McNellis


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

like image 31
Terry Mahaffey Avatar answered Aug 15 '26 01:08

Terry Mahaffey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!