簡體   English   中英

我應該在每個方法上提供 try/catch 還是只提供 main 方法?

[英]Should i provide try/catch on each method, or just the main method?

我一年多以來的做法是為我正在編寫的每個方法提供一個單獨的 try/catch 塊,然后在特定代碼塊失敗時拋出異常對象。 例如:

void MainMethod()
{
    try {
        int num = Method1();
        string str = Method3();
        bool bln = Metho4();
    } catch (Exception Ex) {
        MessageBox.Show(Ex.Message);
    }
}

int Method1() {
    try {
        return 123 + Method2();
    } catch (Exception) {
        throw;
    }
}

int Method2() {
    try {
        return Convert.ToInt32("One Hundred"); // <-- Obviously would fail.
    } catch (Exception) {
        throw;
    }
}

string Method3() {
    try {
        string str1 = "Hello ";

        return str1 + 12345; // <-- Would also fail.
    } catch(Exception) {
        throw;
    }
}

bool Method4() {
    try {
        return true;
    } catch(Exception) {
        throw;
    }
}

我應該提供每個方法自己的/單獨的 try/catch 塊嗎? 或者如果它只是具有 try/catch 的 Main 方法會更好嗎?

謝謝

這真的取決於你想要完成什么。 我更喜歡盡可能在“根”級別捕獲和處理。

在你的情況我會使用try/catch在MainMethod和唯一try/catch其他地方,如果我想捕獲和處理特定的異常,並可能恢復。

暫無
暫無

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

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