[英]Why exception caught without throwing in C++?
我正在运行这个程序。 根据我的理解,try 块中应该有一个错误的分配异常,应该会导致运行时失败。 但是,程序执行没有任何问题。 我有以下问题:
为什么没有运行时错误?
即使没有抛出异常,控件如何到达 catch 块?
#include <iostream> using namespace std; int main() { int b =4, *c = NULL, i=-1; try{ c = new int [i]; b--; }catch (exception& e){ cout << "coming here" << endl; c = new int[1]; b++; } cout << b << endl; return 0; }
由于隐式转换为无符号类型, -1
将转换为std::size_t
值std::numeric_limits<std::size_t>::max()
。 您确实不太可能有那么多 memory 可用。
但是,如果您的操作系统在使用 memory 之前没有实际分配它,则可能不会抛出std::bad_alloc
(在 linux 平台上很常见)。
try 块中的c = new int [i]
会引发异常,因为它无法分配 memory (i=-1),因此将执行 catch 块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.