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

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

问题描述

在Visual Studio 2008 C ++中,如何获得零分错误(而不是其他错误,以及能够访问异常信息)?

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

您首先你需要安装一个结构化异常处理翻译功能,通过调用

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

code> _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天全站免登陆