簡體   English   中英

不使用 catch 塊捕獲的異常。 為什么?

[英]Exceptions not catching using catch block. Why?

因此,在我學習 C# 的第一個項目中,我使用了一些 try/catch 塊。 在大多數情況下,他們工作得很好。 然而,有幾個代碼仍然在異常點中斷,盡管事實上它找到了我預期和希望的確切異常類型。 我將提供發生此問題的代碼示例。

這是我嘗試捕獲異常的地方:

app.MoveFolder(input1, input2);

try {
    //code here
} catch (ArgumentException) {
    //code here
}
break;

這是我創建異常的函數:

public void MoveFolder(string folderPath, string newLocation) {
    this.ThrowExceptionIfFolderDoesntExist(folderPath);

    if (Directory.Exists(newLocation) == true) {
        throw new ArgumentException("example");
    }
    Directory.Move(folderPath, newLocation);
}

ThrowExceptionIfFolderDoesntExist()函數導致:

private void ThrowExceptionIfFolderDoesntExist(string folderPath) {
    if (this.CheckFolderExists(folderPath) == false) {
        throw new ArgumentException("This folder does not exist");
    }
}

因此,如您所見,我的MoveFolder()函數中的此語句和 if 語句都應返回我希望捕獲的ArgumentExceptions 在后一個函數的情況下,這按預期工作。 但是,如果我嘗試將文件夾移動到已存在的位置,則會得到以下信息:

Unhandled Exception: System.ArgumentException: example

這不是我想要的,因為我希望 catch 塊也能處理這個特定的 ArgumentException。 這與認為我指的是特定參數異常的 catch 塊有關嗎? 我原以為它會引用所有 ArgumentExceptions。

我該如何解決這個問題?

為了正確執行 try/catch,您需要執行以下操作:

  1. 將您的方法放在try塊中
  2. catch Exception(s)
  3. throw Exception

這是一些代碼

try
{
    app.MoveFolder(input1, input2);
}
// catch ArgumentException
catch(ArgumentException ex)
{
    throw;
}
// catch all others
catch(Exception ex)
{
    throw;
}

為了捕獲函數拋出的異常,需要在 Try{} 中調用該函數。 您可以按照其他人的說法進行操作,並在 Try 塊中調用 MoveFolder。 如果您在 Try 塊之外拋出異常,它有時會被其他 catch 塊拾取,或者只是未處理並產生錯誤。

try {
    app.MoveFolder(Something1, Something2);
} catch (ArgumentException ex) {
    //Do something with Exception
}

暫無
暫無

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

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