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;
}
}
在上面的例子中是否有更好的方法来处理异常?
在此先感谢您的帮助。
克莱尔
除了Rob Stevenson-Leggetts的回答,我还会让捕捉异常更具体。例如首先捕获一个SqlException,因为它将包含关于实际错误和堆栈跟踪的更多特定信息。 让catch(Exception ex)作为最后的catch-block。 – 2010-08-10 10:02:04