【发布时间】:2017-10-04 08:48:37
【问题描述】:
试图在我的 C++ 程序中添加异常处理,但我发现它很混乱。程序将值 i 和 j 设置为它们的最高可能值并递增它们。我想我希望异常处理能够在整数溢出/环绕发生时检测到它(?)
到目前为止,这是我所拥有的:
#include <iostream>
#include <limits.h>
#include <exception>
#include <stdexcept>
using namespace std;
int main() {
int i;
unsigned int j;
try{
i = INT_MAX;
i++;
cout<<i;
}
catch( const std::exception& e){
cout<<"Exception Error!";
}
try{
j = UINT_MAX;
j++;
cout<<j;
}
catch(const std::exception& e){
cout<<"Exception Error!";
}
}
程序运行,但异常处理部分不起作用。
可能是什么问题?
【问题讨论】:
-
问题是没有指定溢出来抛出异常。因此,如果您期待它,那么您对 C++ 有误解。
-
无符号整数溢出以明确定义的方式环绕。有符号整数溢出会导致undefined behavior,这可能会也可能不会导致回绕,得到一个很大的负数,从而导致崩溃、异常或什至什么都没有发生。
标签: c++ visual-c++ exception-handling integer-overflow