簡體   English   中英

無法在 catch 塊中拋出異常

[英]Cannot throw an exception in catch block

我有一個課程,不應該向最終用戶顯示任何對話框。 如果該用戶傳遞了錯誤的文件路徑,我嘗試拋出異常並在適當的類中處理它。 但是,盡管有“throw”指令,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();
        }
    }

我發現您的 Click 事件處理程序有問題。 您將其定義為異步,但您沒有在等待任何東西。

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

public async Task ReadGuyAsync()

在 loadGuy_Click 方法中,你應該等待它:

await guyManager.ReadGuyAync();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM