除零之外没有被catch块捕获? [英] division by zero is not caught by catch block?
本文介绍了除零之外没有被catch块捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
考虑以下代码块
Hi
consider the following code block
#include<iostream>
int main()
{
int i=0;
try{
int k=9/i;
}
catch(...)
{
std::cout<<"exception occurs"<<std::endl; //control should come here
}
}
当我运行代码未处理的异常时显示并且控件没有去捕获块
为什么会这样?
when I run above code unhandled exception is shown and control doesn't go to catch block
why is it like that?
推荐答案
因为这不是C ++异常,它是浮点数,例如,请参见:如何使用try ... catch来捕获浮点错误? [ ^ ]。
Beacuse that's not a C++ exception, it is a floating point one, see, for instance, here: "How do I use try…catch to catch floating point errors?"[^].
确实发生了 - 我刚测试过它。
It does occur - I just tested it.
int main()
{
int i=0;
try{
int k=9/i;
}
catch(...)
{
std::cout<<"exception occurs"<<std::endl; //control should come here
}
}
它没有出现在您的原始版本中,因为编译器查看代码,看到常量除以常量并将其优化为常量值。然后抱怨在编译时而不是运行时间除以零。
It didn't occur in your original version, because the compiler looked at the code, saw a constant divided by a constant and optimised it to a constant value. And then complained about the divide by zero at compile time instead of run time.
除以零不是C ++异常,因此try-catch块无法捕获它。
以下是一些读物:
捕获异常:除以零点数[[a href =http://stackoverflow.com/questions/6121623/catching-exception-divide-by-zerotarget =_ blanktitle =新窗口> ^ ]
C ++:捕获除零错误 [ ^ ]
如果您使用的是VC ++编译器,则可以使用结构化异常处理。这是一个例子:
Division by zero is not a C++ exception so a try-catch block cannot catch it.
Here are some readings for you:
Catching exception: divide by zero[^]
C++ : Catch a divide by zero error[^]
If you're using a VC++ compiler then you can use structured exception handling for this. Here is an example:
#include <windows.h>
#include <Excpt.h>
int main()
{
int i = 0;
__try
{
int k = 9 / i;
}
__except(_exception_code() == EXCEPTION_INT_DIVIDE_BY_ZERO ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
std::cout << "exception occurs" << std::endl; //control should come here
}
return 0;
}
这篇关于除零之外没有被catch块捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文