如何在Visual Studio 2008 C ++中捕获除以零的错误? [英] How to catch divide-by-zero error in Visual Studio 2008 C++?

查看:339
本文介绍了如何在Visual Studio 2008 C ++中捕获除以零的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Visual Studio 2008 C ++中捕获一个除以0的错误(而不是其他错误;并且能够访问异常信息)?

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++?

我试过这个:

try {
  int j=0;
  int i= 1/j;//actually, we call a DLL here, which has divide-by-zero
} catch(std::exception& e){
  printf("%s %s\n", e.what()); 
}  catch(...){
  printf("generic exception");
}

但是这是通用的... catch块。我理解MS特定的__try可能在某种程度上是有用的,但我更喜欢标准C ++,在任何情况下,我有析构函数阻止使用__try。

But this goes to the generic ... catch block. I understand that the MS-specific __try may be useful here somehow, but I'd prefer standard C++, and in any case I have destructors which prevent the use of __try.

澄清:上面的代码为了讨论的目的而被简化。实际上,除以零是一个错误发生在第三方DLL中,我没有源代码。该错误取决于我传递给库的参数(复杂结构的句柄),但不是以任何明显的方式。

CLARIFICATION: The code above is simplified for discussion purposes. Actually, the divide-by-zero is a bug which occurs deep in a third-party DLL for which I do not have the source code. The error depends on the parameter (a handle to a complex structure) which I pass to the library, but not in any obvious way. So, I want to be able to recover gracefully.

推荐答案

假设你不能简单地修复异常生成的原因代码(也许因为你没有源代码到那个特定的库,也许是因为你不能调整输入参数,在它们引起问题之前)。

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

首先,你需要安装一个结构化异常处理翻译函数,通过调用 _set_se_translator()(请参阅此处),那么您可以检查在发生SEH异常时传递的代码,并抛出相应的C ++异常。

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

然后你可以直接捕获 CMyFunkyDivideByZeroException / code>在C ++中的正常方式。

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.

这篇关于如何在Visual Studio 2008 C ++中捕获除以零的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆