【问题标题】:FileNotFoundException, but catch block is not entered (Async method)FileNotFoundException,但未输入 catch 块(异步方法)
【发布时间】:2016-10-21 15:16:24
【问题描述】:

我有一种方法可以检查文件系统 (UWP) 中是否存在文件:

private async Task<bool> FileExistsAsync(string filename)
    {
        try
        {
            if (filename != null)
            {
                var item = await StorageFile.GetFileFromPathAsync(filename); // FileNotFoundException happens here
                if (item != null)
                    return true;
            }
            return false;
        }
        catch (Exception e) // I Expect the debugger to handle the FileNotFoundException here, but it never happens
        {
            return false;
        }
    }

当我尝试使用StorageFile.GetFileFromPathAsync 获取不存在的文件时,我遇到了异常。由于某种原因,我的 catch 块没有处理它,而是看起来像这样:

我的尝试

  • 显式处理FileNotFoundException
  • 在 if 语句中添加 Try-catch-block

请注意,该方法需要保持异步,因为我在此方法中还有其他内容,我删除了这些内容以提供Minimal, Complete, and Verifiable example

为什么在抛出 FileNotFoundException 时调试器没有进入我的 catch 块?

【问题讨论】:

  • 试试这个。捕捉(异常){返回假; }
  • @vivek 它没有改变任何东西。另外,我需要代码中的参数(正如我所说,我删除了一些不必要的部分)

标签: c# exception asynchronous exception-handling uwp


【解决方案1】:

在异常弹出窗口中,我看到了[x] Break when this exception type is thrown。尝试在此处禁用它,或从“异常设置”对话框(我的系统上的 Ctrl-Alt-E,或菜单“调试”>“Windows”>“异常设置”)。

【讨论】:

  • 谢谢,这就是我的问题。 :)
【解决方案2】:
 var item = await StorageFile.GetFileFromPathAsync(filename); 

你有在这个函数中尝试和捕捉吗?如果是,请添加

throw 

赶上

试试这个:Why can't I catch an exception from async code? 而这个:Catch an exception thrown by an async method 可以帮助你。

【讨论】:

  • 我无法更改GetFileFromPathAsync 的代码,因为它来自Windows.Storage 命名空间。
猜你喜欢
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多