代码如何在异常后执行?

Bob*_*orn 6 c# exception visual-studio-debugging

我必须遗漏一些东西......如何抛出异常,但异常后的代码仍会在调试器中被击中?

private UpdaterManifest GetUpdaterManifest()
{
    string filePathAndName = Path.Combine(this._sourceBinaryPath, this._appName + ".UpdaterManifest");

    if (!File.Exists(filePathAndName))
    {
        // This line of code gets executed:
        throw new FileNotFoundException("The updater manifest file was not found. This file is necessary for the program to run.", filePathAndName);
    }

    UpdaterManifest updaterManifest;

    using (FileStream fileStream = new FileStream(filePathAndName, FileMode.Open))
    {
        // ... so how is it that the debugger stops here and the call stack shows
        // this line of code as the current line? How can we throw an exception
        // above and still get here?
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(UpdaterManifest));
        updaterManifest = xmlSerializer.Deserialize(fileStream) as UpdaterManifest;
    }

    return updaterManifest;
}
Run Code Online (Sandbox Code Playgroud)

Abe*_*bel 5

某些情况通常会发生这种情况:

  • 当关闭"要求源文件与原始版本完全匹配"选项时.在这种情况下,当文件不同步时,您不会收到警告.

  • 当IDE要求"存在构建错误时.你想继续并运行最后一次成功的构建吗?" ,在这种情况下IDE可能是错误的正确的行,因为它运行早期版本.

  • 当您调试代码的发布版本时,某些部分会被优化掉.这导致突出显示的行成为源中的下一个可用行,它反映了优化代码中的实际语句(在使用优化的外部程序集进行调试时,您经常会看到这一行).


编辑:我有点误读你的代码.在"throw"和突出显示的行之间,只有一个变量的声明,根本没有代码可以执行.我假设您的意思是"使用..."代码突出显示了?因为这是预期的:它是throw语句之后的第一行(throw语句本身没有"捕获"调试器的错误).

看截图: 在此输入图像描述

  • @BobHorn:你应该看到这样的:调试器会在每次抛出时中断,并且它会在抛出之后立即停止在语句上(通常是它解开的行).您可以通过选中"仅对用户未处理的异常进行分解"(或删除此特定异常的复选框)并在catch子句中添加手动断点来解决此问题. (2认同)