Catching exception in code

落爺英雄遲暮 提交于 2019-12-10 16:07:00

问题


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?


回答1:


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



回答2:


You are catching exceptions generated by Microsoft's structured exception handling (SEH) layer, which is an operating system thing specific to Microsoft. As Mykola suggested, you may need to fiddle with your compiler options, but be aware that this code will then not be portable to other operating systems or even to other compilers running on Windows.




回答3:


Go to your project properties, Under C/C++, Code Generation, you'll find "Enable C++ Exceptions". change this option to "Yes, With SEH Exceptions"

Mind you that you will only be able to catch these kind of exceptions using either:

  • try {} catch(...) {} (with the ellipsis)
  • __try {} __except() {} (with a proper filter in the __except)
  • by Using SetUnhandledExceptionFilter()

For valid values in the __except see here




回答4:


In Visual Studio case it can be a Compiler options. But by standard the exception won't be thrown.



来源:https://stackoverflow.com/questions/623373/catching-exception-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!