异常处理 - 有更好的方法吗?
public bool AddEntity(int ParentId, 字符串描述) { 尝试 { _connection.Open(); SqlCommand 命令 = new SqlCommand("INSERT 结构(路径,描述)" + "VALUES(" + GetPath(parentId) + ".GetDescendant(" + GetLastChildPath(parentId, 1) + ", NULL), " + 描述+“)”,_连接);
if (command.ExecuteNonQuery() <= 0) _success = false;
command.Connection.Close();
if (_success)
{
return true;
}
throw new Exception("An error has occured whilst trying to add a entity");
}
catch (Exception ex)
{
AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex));
return false;
}
}
有没有更好的方法来处理上面示例中的异常?
预先感谢您的任何帮助。
克莱尔
public bool AddEntity(int parentId, string description)
{
try
{
_connection.Open();
SqlCommand command = new SqlCommand("INSERT Structure (Path,Description) " +
"VALUES(" + GetPath(parentId) + ".GetDescendant(" + GetLastChildPath(parentId, 1) + ", NULL), " +
description + ")", _connection);
if (command.ExecuteNonQuery() <= 0) _success = false;
command.Connection.Close();
if (_success)
{
return true;
}
throw new Exception("An error has occured whilst trying to add a entity");
}
catch (Exception ex)
{
AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex));
return false;
}
}
Is there a better way of handling the exceptions in the example above?
Thanks in advance for any help.
Clare
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有很多问题。
一个。您正在使用内联 SQL 并将我只能假设为用户生成的数据注入其中。这是一个安全风险。使用参数化查询。
b.您的异常处理没问题,但是如果发生错误,这将使连接保持打开状态。我会这样写:
There's quite a few things wrong here.
a. You're using inline SQL and injecting what I can only assume to be user generated data into it. This is a security risk. Use a parameterised query.
b. You're exception handling is ok but this will leave the connection open if an error occurs. I'd write it like so:
您可以利用 IDisposable 接口以及
using
块的强大功能。即使抛出异常,这也会关闭连接。它变成(或多或少)这样:
在这种情况下,Dispose 将关闭连接。
You can take advantage of the IDisposable interface, and the power of a
using
block.This will close the connection even if an exception is thrown. It turns into (more-or-less) this:
Dispose, in this case, will close the connection.