B. *_*non 3 c# resharper sqlexception catch-block rethrow
ReSharper建议重新抛出异常然后,当我这样做时,它表示整个catch子句无论如何都是多余的,并建议将其删除.
我(从MethodMan使用此代码在这里):
public static DataTable ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(UsageRptConstsAndUtils.CPSConnStr))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (SqlException ex)
{
throw;
}
return ds.Tables[0];
}
}
Run Code Online (Sandbox Code Playgroud)
当我在解决方案中有ReSharper Inspect> Code Issues时,它想知道"异常重新抛出可能是否有意":
catch (SqlException ex)
{
throw ex;
}
Run Code Online (Sandbox Code Playgroud)
如果我接受ReSharper的建议修复("rethrow exception"),Resharper将删除"ex":
catch (SqlException ex)
{
throw;
}
Run Code Online (Sandbox Code Playgroud)
......但是,在接下来的检查中,它说,"catch子句是多余的",并建议将其完全删除.
但是,当然,如果我删除catch块,它将无法编译("预期捕获或最终").我可以删除尝试...但是...如果我将其更改为:
catch (SqlException sqlex)
{
for (int i = 0; i < sqlex.Errors.Count; i++)
{
var sqlexDetail = String.Format("From
ExecuteDataSet(), SQL Exception #{0}{1}Source: {2}{1}
Number: {3}{1}State: {4}{1}Class: {5}{1}Server: {6}{1}Message: {7}
{1}Procedure: {8}{1}LineNumber: {9}",
i + 1, // Users would get the fantods if they
saw #0
Environment.NewLine,
sqlex.Errors[i].Source,
sqlex.Errors[i].Number,
sqlex.Errors[i].State,
sqlex.Errors[i].Class,
sqlex.Errors[i].Server,
sqlex.Errors[i].Message,
sqlex.Errors[i].Procedure,
sqlex.Errors[i].LineNumber);
MessageBox.Show(sqlexDetail);
}
}
catch (Exception ex)
{
String exDetail
String.Format(UsageRptConstsAndUtils.ExceptionFormatString, ex.Message,
Environment.NewLine, ex.Source, ex.StackTrace);
MessageBox.Show(exDetail);
}
Run Code Online (Sandbox Code Playgroud)
... ReSharper的检查没有抱怨.
当你这样做时,你正在重置调用堆栈,这会丢失有关首先抛出异常的有价值信息.
catch (SqlException ex)
{
throw ex;
}
Run Code Online (Sandbox Code Playgroud)
如果ReSharper更聪明,它会告诉你首先删除那个部分,节省你重写代码部分所花费的时间.
以下代码更好,因为它不会丢失堆栈跟踪信息,但它是不必要的.
catch (SqlException ex)
{
throw;
}
Run Code Online (Sandbox Code Playgroud)
即使您省略了上述内容,异常也会"冒泡",并且可以在程序中的某个位置进一步捕获,无论您准备好在哪里处理它(记录它,或显示消息,或者采取一些替代行动等).
| 归档时间: |
|
| 查看次数: |
445 次 |
| 最近记录: |