Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在引发异常时引发异常_C++_Exception Handling - Fatal编程技术网

C++ 在引发异常时引发异常

C++ 在引发异常时引发异常,c++,exception-handling,C++,Exception Handling,此代码: #include <iostream> #include <stdexcept> using namespace std; int throw_it() { throw range_error( "foo" ); } int main() { try { throw throw_it(); } catch ( exception const &e ) { cerr << e.what() <<

此代码:

#include <iostream>
#include <stdexcept>

using namespace std;

int throw_it() {
  throw range_error( "foo" );
}

int main() {
  try {
    throw throw_it();
  }
  catch ( exception const &e ) {
    cerr << e.what() << endl;
    return 0;
  }
}

一次只能计算一个异常。从15.1/7开始

如果异常处理机制在完成对要抛出的表达式的求值之后但在捕获异常之前调用通过异常退出的函数,则调用std::terminate

在您的示例中,未调用
std::terminate()
,因为实际上只引发了一个异常。当
抛出时抛出它()时,首先计算
throw\u it()
,这将导致在实际引发异常之前调用函数。由于函数抛出异常且从不返回原始的
throw,因此从未到达。如果
throw\u it()
未引发异常并返回整数值,则将执行调用throw表达式。因此,对于您的示例,保证打印
foo

但是,如何从活动处理程序中抛出新异常呢?捕获异常时,它已被完全评估。当您抛出一个新异常(而不是用“throw;”重新抛出)时,原始异常将被销毁,新异常的计算将开始

从15.1/4开始

异常对象在异常的最后一个剩余活动处理程序通过任何方式退出后被销毁,而不是通过重试或

这满足了一次只能评估一个异常的规则

更具体地说,在 在定义的行为中引发异常结果

只要它不是在构造异常对象之后和捕获它之前,就可以了,因为这样会调用
std::terminate
。在您的示例中,根本没有创建异常对象,因此没有要抛出的内容,而是抛出
range\u error(“foo”)
。这是一个值得注意的例外

您可以通过以下方式进行检查:

int throw_it() {
    throw range_error( "foo" );
    return 19;
}

int main() {
    try {
        try { // nested try is perfectly legal
            throw throw_it();
        } catch (...) {
            cerr << "not good!";
        }
    } catch (exception const &e) {
        cerr << e.what() << endl;
        return 0;
    }
}

我现在太累了,但是似乎是一个有趣的文章,关于这个话题。“StfFalk Windows SEH和C++异常是两个不同的事情。你不是在“抛出异常的过程中”。您正在调用一个函数并计划使用它的返回值进行抛出,但是当函数没有实际返回时,您的计划就被破坏了。
int throw_it() {
    throw range_error( "foo" );
    return 19;
}

int main() {
    try {
        try { // nested try is perfectly legal
            throw throw_it();
        } catch (...) {
            cerr << "not good!";
        }
    } catch (exception const &e) {
        cerr << e.what() << endl;
        return 0;
    }
}
not good!

RUN SUCCESSFUL (total time: 59ms)