Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exception in code

I was trying this piece of code to check whether the divide by zero exception is being caught:

int main(int argc, char* argv[])
{
    try
    {
      //Divide by zero
        int k = 0;
        int j = 8/k;
    }
    catch (...)
    {
        std::cout<<"Caught exception\n";
    }
    return 0;
}

When I complied this using VC6, the catch handler was executed and the output was "Caught exception". However, when I compiled this using VS2008, the program crashed without executing the catch block. What could be the reason for the difference?

like image 756
Naveen Avatar asked Mar 01 '23 22:03

Naveen


1 Answers

Enable structured exception handling under project -> properties -> configuration properties -> c/c++ -> code generation -> enable c++ exceptions.

Use a try except. Ideally with a filter that checks the exception code then returns the constant signalling if it would like to catch. I have skipped that out here but I recommend you see here for examples of the filter.

#include <iostream>
#include <windows.h>

int main(int argc, char* argv[])
{
    __try
    {
        //Divide by zero
        int k = 0;
        int j = 8/k;
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        if(GetExceptionCode()==EXCEPTION_INT_DIVIDE_BY_ZERO)
            std::cout << "Caught int divison exception\n";
        else
            std::cout << "Caught exception\n";

        system("pause");
    }
    return 0;
}
like image 78
Tim Matthews Avatar answered Mar 11 '23 19:03

Tim Matthews