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

后端 未结 9 2409
清歌不尽
清歌不尽 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:59

    Try the following code:

    try
    { 
      const int j=0;
      if (j == 0) { throw std::exception("j was 0"); } 
      const int i= 1/j;    
    }
    catch(std::exception& e)
    { 
      printf("%s %s\n", e.what());  
    }
    catch(...)
    { 
      printf("generic exception"); 
    }
    

    Of course, if you're OK doing this without exceptions, you could do:

    const int j = 0;
    if (j == 0)
    {
      /* do something about the bad pre-condition here */
    }
    else
    {
      const int i = 1 / j;
    }
    

    Edit in response to clarification: you'll have to figure out what input it is that you're handing the third party that causes them to divide by zero before-hand, and handle that before ever calling their function.

提交回复
热议问题