【发布时间】: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