【问题标题】:try/catch and returning values尝试/捕获并返回值
【发布时间】:2016-05-02 20:51:53
【问题描述】:

我有一个返回List 的方法。现在我想知道如何正确放置try/catch 块。如果我将 return 语句放在 try 中,我会收到错误

并非所有代码路径都返回值

如果我放在catch 之后(就像我现在正在做的那样),即使在Exception 之后,它也会返回products。那么最好的方法应该是什么?

方法如下:

public List<Product> GetProductDetails(int productKey)
{
    List<Product> products = new List<Product>();
    try
    {
       using (SqlConnection con = new SqlConnection(_connectionString))
       {
         SqlCommand cmd = new SqlCommand("usp_Get_ProductDescription", con);
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@riProductID", productKey);
         con.Open();
         using (SqlDataReader reader = cmd.ExecuteReader())
         {
           while (reader.Read())
           {
             Product product = new Product(reader["Name"].ToString(), reader["Code"].ToString());
             products.Add(product);
           }
         }
       }
     }
     catch { }
     return products;
}

【问题讨论】:

  • 有史以来最糟糕的错误处理方式。
  • 你为什么使用一个空的 catch 块?
  • 如果发生异常,您希望发生什么?您是否希望它返回迄今为止找到的所有产品?跳过任何导致错误的产品?返回一个空列表?返回空?

标签: c# methods exception-handling return try-catch


【解决方案1】:

目前,如果抛出异常,您不会返回任何内容。 使用try, catch, finally。 (更多官方信息请关注MSDN page)

try
{
    //try to execute this code
}
catch
{
    //execute this if an exception is thrown
}
finally
{
    //execute this code, after try/catch
}

因此,如果您将 return 语句放入 finally 部分,即使抛出异常,您也会返回您的列表...

【讨论】:

    【解决方案2】:

    删除完整的 Try 和 Catch 块。显然你无法处理 GetProductDetails 方法中的异常,所以让它们被抛出。

    但是调用代码可以做出决定:

    IList<Product> products = null;
    
    try
    {
        products = GetProductDetails(3);
    }
    catch(Exception ex)
    {
        // Here you can make the decision whether you accept an empty list in case of retrieval errors.
        // It is the concern of this method, not of the ProductDetails method.
        // TODO: Use logging
        products = new List<Product>();
    }
    

    如果您必须使用GetProductDetails 方法在每个方法中编写此代码,我可以想象这感觉就像代码重复。但是考虑一下,当您有 X 实现时,您希望对无法获得产品详细信息做出不同的反应。您将不得不想出解决方法。您甚至可能会遇到难以解决的奇怪错误。

    【讨论】:

    • 您能否建议任何好的资源,让我可以了解错误处理以及必须始终捕获哪些异常?我问是因为很多人建议在这篇文章之后处理异常
    • @HumaAli 很多人倾向于直接解决您的问题。如果您想在方法中处理异常,它们是正确的。但是,我提出了一个更好的设计,它完全消除了您最初的问题。
    • 这可能很有趣,即使它是 Java。 stackoverflow.com/q/18679090/296526
    • 是的,我意识到了!在这种情况下,你的答案是完美的!
    【解决方案3】:

    这取决于在特殊情况下应该发生什么。如果这可能由于某种原因而发生,而该原因还不足以让应用程序崩溃,或者如果您能够适当地处理该异常,那么您可以使用当前的方法 - 但是您绝对应该至少留下一条日志消息在包含已抛出错误的 catch 子句中:

    catch (Exception e) 
    { 
        log.Info(e.Message);
    }
    

    通过这种方式,您可以获得列表中的所有结果,但导致任何异常的结果除外。您可以简单地继续处理您获得的所有结果并忽略那些错误(假设您以任何方式记录它们)。

    如果这是一个非常意外的行为(这是异常的预期行为,这就是为什么它们被称为异常)你应该从你的方法中删除所有这些 try/catch 并处理方法之外的任何异常,正如 Maurice 已经提到的.

    【讨论】:

    • 您能否建议任何好的资源,让我可以了解错误处理以及必须始终捕获哪些异常?我问是因为很多人建议在这篇文章之后处理异常
    猜你喜欢
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2012-06-14
    • 1970-01-01
    相关资源
    最近更新 更多