【问题标题】:Cannot throw an exception in catch block不能在 catch 块中抛出异常
【发布时间】:2020-03-28 13:30:28
【问题描述】:

我有一个类,不应该向最终用户显示任何对话框。万一该用户传递了错误的文件路径,我尝试抛出异常并在适当的类中处理它。 但是,尽管有“抛出”指令,Visual Studio 仍会显示异常对话框并在其发生后中断应用程序(调试模式)。在发布模式下,应用程序在提供错误的文件路径后会崩溃。我做错了什么?

GuyManager.cs:

private IStorageFile latestGuyFile;
public IStorageFile LatestGuyFile { get { return latestGuyFile; } }
public string Path { get; set; }


 public async void ReadGuyAsync()
    {
        if (String.IsNullOrWhiteSpace(Path))
            return;

        try
        {
            latestGuyFile = await StorageFile.GetFileFromPathAsync(Path);
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Error occured: " +ex.Message);
            Debug.WriteLine(ex.StackTrace);
            throw;
        }

MainPage.xml.cs:

private async void loadGuy_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            guyManager.ReadGuyAsync();
        }
        catch (Exception ex)
        {
            MessageDialog dialog = new MessageDialog("Error" + ex.Message);
            await dialog.ShowAsync();
        }
    }

【问题讨论】:

    标签: c# winforms xaml try-catch


    【解决方案1】:

    我发现您的 Click 事件处理程序存在问题。 您将其定义为异步,但您没有等待任何东西。

    您应该更改 ReadGuyAsync 方法以返回 Task 而不是 void,如下所示:

    public async Task ReadGuyAsync()

    在 loadGuy_Click 方法中,你应该等待它:

    await guyManager.ReadGuyAync();

    【讨论】:

    • 好吧,在 Click 事件处理程序中,我正在等待 MessageDialog 弹出窗口的结果。将返回值从 void 更改为 Task 解决了问题,您能否给我更多信息,为什么它会这样工作?真的很感激这个
    • 哦,是的,没注意到。但问题是存在的。您应该等待 ReadGuyAsync() 调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2012-09-21
    • 2011-03-25
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多