How to catch divide-by-zero error in Visual Studio 2008 C++?

后端 未结 9 2407
清歌不尽
清歌不尽 2020-12-19 06:26

How can I catch a divide-by-zero error (and not other errors; and to be able to access exception information) in Visual Studio 2008 C++?

I tried this:



        
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-19 06:57

    Assuming that you can't simply fix the cause of the exception generating code (perhaps because you don't have the source code to that particular library and perhaps because you can't adjust the input params before they cause a problem).

    You have to jump through some hoops to make this work as you'd like but it can be done.

    First you need to install a Structured Exception Handling translation function by calling _set_se_translator() (see here) then you can examine the code that you're passed when an SEH exception occurs and throw an appropriate C++ exception.

    void CSEHException::Translator::trans_func(
        unsigned int code, 
        EXCEPTION_POINTERS *pPointers)
    {
       switch (code)
       {
           case FLT_DIVIDE_BY_ZERO : 
              throw CMyFunkyDivideByZeroException(code, pPointers);
           break;
       }
    
       // general C++ SEH exception for things we don't need to handle separately....
       throw CSEHException(code, pPointers);
    }
    

    Then you can simply catch your CMyFunkyDivideByZeroException() in C++ in the normal way.

    Note that you need to install your exception translation function on every thread that you want exceptions translated.

提交回复
热议问题