【问题标题】:Should i provide try/catch on each method, or just the main method?我应该在每种方法上提供 try/catch,还是只提供主要方法?
【发布时间】:2017-09-25 05:28:53
【问题描述】:

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

谢谢

【问题讨论】:

  • 这取决于你想如何处理你的异常。
  • 在你的例子中,你只能使用MainMethod的块。
  • 根据我的观点,我只会在MainMethod() 中使用try/catch
  • 我建议在你的 main 方法上设置一个 try catch 块,但是我建议你把你的逻辑放到 try catch 并等待异常引发。检查空对象或在转换时尝试强制转换等可以有效地使用。
  • 只有在子方法执行某种算术或次要过程时才会这样,对吗?如果他们正在访问数据访问层并就使用数据库事务而言,那嵌套的try/catch 块将受益,对吧?我的意思是,回滚交易必须在 Catch Block 上进行。

标签: c# methods nested try-catch


【解决方案1】:

这真的取决于你想要完成什么。我更喜欢尽可能在“根”级别捕获和处理。

如果我想捕获和处理特定异常并可能恢复,我会在 MainMethod 中使用 try/catch,而在其他任何地方只使用 try/catch

【讨论】:

  • 我明白了,根据我的示例 - 我也可以清楚地决定只在 MainMethod 上提供一个 try/catch。但是,我在想,如果这些“子”方法在专门涉及数据库事务的数据访问层上工作,那么嵌套的 try/catch 将受益,假设我将在 Catch 块上回滚事务。我说的对吗?
  • 从您的示例开始,正确。或者,如果您在 AWS、Azure 等中运行,您可能希望捕获特定的连接异常类型并使用重试系统来建立连接
  • 然后在DAL方法中提供try/catch,如果发生任何异常,则回滚您的事务并抛出异常。即catch(Exception exp){ db.Rollback(); throw exp; }。此异常将在MainMethod 中捕获。
  • 记住在重新抛出异常时不要使用throw exp;,而是使用throw;。否则你的调用堆栈将不正确
  • 使用 throw exp; 而不是 throw; 有什么复杂性?我的意思是,差别真的那么大吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多