我应该为每种方法提供try / catch,还是只提供main方法?

时间:2017-09-25 05:28:53

标签: c# methods nested try-catch

我一年多的练习是为我正在编写的每个方法提供一个单独的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的主方法会更好吗?

由于

1 个答案:

答案 0 :(得分:1)

这实际上取决于你想要完成的事情。我希望尽可能抓住并处理“根”级别。

在你的情况下,我会在MainMethod中使用try/catch,在其他地方只使用try/catch,如果我想捕获并处理特定异常并可能恢复。