Visual Studio 调试继续未处理的异常

Visual Studio debug continuing unhandled exception

我在 Visual Studio(2008 年和 2013 年)中发现了一个奇怪的行为。

让我们从测试代码开始:

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

string readFile()
{
    std::fstream f;
    f.open("not_good_file.txt", std::fstream::in);

    if (!f.good())
        throw std::exception("unable to read file");

    f.seekg(0, f.end);
    std::streamoff len = f.tellg();
    f.seekg(0, f.beg);

    string result(len, '[=11=]');
    f.read(&result[0], len);
    f.close();
    return result;
}

int main(int argc, char** argv)
{
    cout << "before exception" << endl;
    readFile();
    cout << "after exception" << endl;
    return 0;
}

当 运行 没有调试器时,应用程序会按预期中止,但是当我在调试时遇到无人看守的异常时,会显示已知消息 window 告诉我未捕获的异常。我得到 break 的选项,它显示抛出异常的行(如果可用)和 continue 选项(如名称所示)继续应用程序。

结果是,异常后的代码直接被执行,这意味着 f.tellg() returns -1 这不是 std::string 的有效长度。

为什么会这样?

The result is, that code directly after the exception is executed wich means that f.tellg() returns -1 wich is no valid length for std::string.

调试器为您提供选项 运行 就好像异常不存在一样(继续)或在异常站点中断(中断)。

通常情况下,当您选择继续时,应用程序应跳转到异常的 catch 块(或堆栈 unwindingm 和 then 到 catch 块)。但是你没有 catch 块,所以应用程序应该跳转到 std::terminate(并结束执行)。

让 IDE 为您提供 "continue" 的选项,这意味着 "call std::terminate" 是疯狂的(因为那样的话,"continue" 实际上意味着 "stop") .所以在这种情况下,"continue" 表示 "continue execution as if the exception was not there",而不是 "continue execution to terminate application"。