|
asdfgty 0 / 0 / 0 Регистрация: 05.05.2017 Сообщений: 16 |
||||
|
1 |
||||
|
24.09.2018, 17:21. Показов 1508. Ответов 1 Метки нет (Все метки)
__________________
0 |
What Is It?
This exception means that you’re trying to access a collection item by index, using an invalid index. An index is invalid when it’s lower than the collection’s lower bound or greater than or equal to the number of elements it contains.
When It Is Thrown
Given an array declared as:
byte[] array = new byte[4];
You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException to be thrown. Remember this when you create and access an array.
Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1 (where Length is total number of items in the array) so this code doesn’t work:
array[array.Length] = 0;
Moreover please note that if you have a multidimensional array then you can’t use Array.Length for both dimension, you have to use Array.GetLength():
int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
for (int j=0; j < data.GetLength(1); ++j) {
data[i, j] = 1;
}
}
Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color. Each item represents a pixel, indices are from (0, 0) to (imageWidth - 1, imageHeight - 1).
Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
for (int y = 0; y <= imageHeight; ++y) {
pixels[x, y] = backgroundColor;
}
}
This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]:
pixels[imageWidth, imageHeight] = Color.Black;
In another scenario you may get ArgumentOutOfRangeException for this code (for example if you’re using GetPixel method on a Bitmap class).
Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can’t grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>(), this example adds a new entry to an existing array:
Array.Resize(ref array, array.Length + 1);
Don’t forget that valid indices are from 0 to Length - 1. If you simply try to assign an item at Length you’ll get IndexOutOfRangeException (this behavior may confuse you if you think they may increase with a syntax similar to Insert method of other collections).
Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:
var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });
In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.
Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:
private static string[] RomanNumbers =
new string[] { "I", "II", "III", "IV", "V" };
public static string Romanize(int number)
{
return RomanNumbers[number];
}
Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it’s also a well-known convention in use from many years) if they didn’t find anything. Let’s imagine you have an array of objects comparable with a string. You may think to write this code:
// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.IndexOf(myArray, "Debug")]);
// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);
This will fail if no items in myArray will satisfy search condition because Array.IndexOf() will return -1 and then array access will throw.
Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):
static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
int[] result = new int[maximum + 1]; // Includes 0
foreach (int number in numbers)
++result[number];
return result;
}
Of course, it’s a pretty terrible implementation but what I want to show is that it’ll fail for negative numbers and numbers above maximum.
How it applies to List<T>?
Same cases as array — range of valid indexes — 0 (List‘s indexes always start with 0) to list.Count — accessing elements outside of this range will cause the exception.
Note that List<T> throws ArgumentOutOfRangeException for the same cases where arrays use IndexOutOfRangeException.
Unlike arrays, List<T> starts empty — so trying to access items of just created list lead to this exception.
var list = new List<int>();
Common case is to populate list with indexing (similar to Dictionary<int, T>) will cause exception:
list[0] = 42; // exception
list.Add(42); // correct
IDataReader and Columns
Imagine you’re trying to read data from a database with this code:
using (var connection = CreateConnection()) {
using (var command = connection.CreateCommand()) {
command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
ProcessData(reader.GetString(2)); // Throws!
}
}
}
}
GetString() will throw IndexOutOfRangeException because you’re dataset has only two columns but you’re trying to get a value from 3rd one (indices are always 0-based).
Please note that this behavior is shared with most IDataReader implementations (SqlDataReader, OleDbDataReader and so on).
You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with
var data = dr["Colum1"]; // Missing the n in Column1.
This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn’t exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of «Colum1».
Others
There is another (documented) case when this exception is thrown: if, in DataView, data column name being supplied to the DataViewSort property is not valid.
How to Avoid
In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you’re developing a library), you may need to replace 0 with GetLowerBound(0) and .Length with GetUpperBound(0) (of course if you have parameters of type System.Array, it doesn’t apply for T[]). Please note that in this case, upper bound is inclusive then this code:
for (int i=0; i < array.Length; ++i) { }
Should be rewritten like this:
for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }
Please note that this is not allowed (it’ll throw InvalidCastException), that’s why if your parameters are T[] you’re safe about custom lower bound arrays:
void foo<T>(T[] array) { }
void test() {
// This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}
Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException or ArgumentOutOfRangeException). In the next example, wrong parameters may cause IndexOutOfRangeException, users of this function may expect this because they’re passing an array but it’s not always so obvious. I’d suggest to always validate parameters for public functions:
static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
if (from < 0 || from>= array.Length)
throw new ArgumentOutOfRangeException("from");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (from + length > array.Length)
throw new ArgumentException("...");
for (int i=from; i < from + length; ++i)
array[i] = function(i);
}
If function is private you may simply replace if logic with Debug.Assert():
Debug.Assert(from >= 0 && from < array.Length);
Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert(), throw a proper exception (more descriptive about the problem) or handle that like in this example:
class Table {
public int SelectedIndex { get; set; }
public Row[] Rows { get; set; }
public Row SelectedRow {
get {
if (Rows == null)
throw new InvalidOperationException("...");
// No or wrong selection, here we just return null for
// this case (it may be the reason we use this property
// instead of direct access)
if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
return null;
return Rows[SelectedIndex];
}
}
Validate Return Values
In one of previous examples we directly used Array.IndexOf() return value. If we know it may fail then it’s better to handle that case:
int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }
How to Debug
In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you’ll need to debug your code. First of all, read this Eric Lippert’s blog post about debugging of small programs, I won’t repeat his words here but it’s absolutely a must read.
You have source code, you have exception message with a stack trace. Go there, pick right line number and you’ll see:
array[index] = newValue;
You found your error, check how index increases. Is it right? Check how array is allocated, is coherent with how index increases? Is it right according to your specifications? If you answer yes to all these questions, then you’ll find good help here on StackOverflow but please first check for that by yourself. You’ll save your own time!
A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can’t figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you’ll see exactly which line throws this exception, which array is involved and which index you’re trying to use. Really, 99% of the times you’ll solve it by yourself in a few minutes.
If this happens in production then you’d better to add assertions in incriminated code, probably we won’t see in your code what you can’t see by yourself (but you can always bet).
The VB.NET side of the story
Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.
In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.
' declares an array with space for 5 integer
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer
So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException
For i As Integer = 0 To 4
myArray(i) = i
Next
The VB.NET rule
This exception means that you’re trying to access a collection item by index, using an invalid index. An index is invalid when it’s lower than the collection’s lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration
I’m trying to implement this algorithm using Razor, but, I got this exception
System.IndexOutOfRangeException: Index was outside the bounds of the array.
@{
//....
for (int i = tab[0]; i <= tab[4]; i++)
{
if (i == pagination.numPageCourrante)
{
<li class="active"><a href="#">@i <span class="sr-only">(current)</span></a></li>
}
else
{//from here the exception triggers
<li><a href="/Accueil/Rechercher?rech=micro&type=nomAppMetier&num=@(tab[i])">@i </a></li>
}
}
}
Knowing that the declaration of the table is :
int[] tab = new int[5];
Thanks a lot !
Soner Gönül
95.9k102 gold badges205 silver badges356 bronze badges
asked Jan 30, 2014 at 8:50
3
Seems like your logic is wrong.
What if your tab[4] will be 10? Your loop will work 10 times with this case but your array doesn’t have 10 items. That’s why probably you get IndexOutOfRangeException in your example. tab[4] will probably bigger than 4 and that’s why your program try to access some index that your array doesn’t have.
Arrays are zero-indexed. When you define an array with 5 items with;
int[] tab = new int[5];
You can access items indexed 0 to 4.
Sounds like you just need to use it like;
int[] tab = new int[5];
for (int i = 0; i < tab.Length ; i++)
{
if (tab[i] == pagination.numPageCourrante)
{
//...
}
}
answered Jan 30, 2014 at 8:54
Soner GönülSoner Gönül
95.9k102 gold badges205 silver badges356 bronze badges
I suppose you don’t want to use the values in the array as start and end of your for-loop. In order to make it work, you can do either of the following:
for (int i = 0; i < tab.Length; i++)
{
var value = tab[i];
// use value ...
}
Or, you can also use foreach:
foreach(int value in tab)
{
// use value ...
}
answered Jan 30, 2014 at 8:55
![]()
MarkusMarkus
20.5k4 gold badges29 silver badges53 bronze badges
Your different i values are : tab[0], tab[1], tab[2], tab[3], tab[4].
Then when you call tab[i] you actually call tab[tab[x]]. With x being successively 0, 1, 2, 3, 4. Then if any of your tab value is not in the interval [0, 4], for example 12, you try to reach tab[12] and IndexOutOFRangeException is thrown.
It is certainly where the mistake is if you want to simply loop through your array.
The two correct way to do it are with a for loop :
for (int i = 0; i < tab.Length; i++)
{
// Your code here
}
or with a foreach loop :
foreach(int i in tab)
{
// Your code here
}
answered Jan 30, 2014 at 8:59
if u enter like that…u can get the bound error in html array:
here the error happened in name
<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"+@i, new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID"[@i], @disabled="disabled" })</td>
instead of that:use like that
<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"+@i, new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID[@i]", @disabled="disabled" })</td>
answered Sep 8, 2015 at 11:10
Deepan RajDeepan Raj
1943 silver badges11 bronze badges
I’m trying to implement this algorithm using Razor, but, I got this exception
System.IndexOutOfRangeException: Index was outside the bounds of the array.
@{
//....
for (int i = tab[0]; i <= tab[4]; i++)
{
if (i == pagination.numPageCourrante)
{
<li class="active"><a href="#">@i <span class="sr-only">(current)</span></a></li>
}
else
{//from here the exception triggers
<li><a href="/Accueil/Rechercher?rech=micro&type=nomAppMetier&num=@(tab[i])">@i </a></li>
}
}
}
Knowing that the declaration of the table is :
int[] tab = new int[5];
Thanks a lot !
Soner Gönül
95.9k102 gold badges205 silver badges356 bronze badges
asked Jan 30, 2014 at 8:50
3
Seems like your logic is wrong.
What if your tab[4] will be 10? Your loop will work 10 times with this case but your array doesn’t have 10 items. That’s why probably you get IndexOutOfRangeException in your example. tab[4] will probably bigger than 4 and that’s why your program try to access some index that your array doesn’t have.
Arrays are zero-indexed. When you define an array with 5 items with;
int[] tab = new int[5];
You can access items indexed 0 to 4.
Sounds like you just need to use it like;
int[] tab = new int[5];
for (int i = 0; i < tab.Length ; i++)
{
if (tab[i] == pagination.numPageCourrante)
{
//...
}
}
answered Jan 30, 2014 at 8:54
Soner GönülSoner Gönül
95.9k102 gold badges205 silver badges356 bronze badges
I suppose you don’t want to use the values in the array as start and end of your for-loop. In order to make it work, you can do either of the following:
for (int i = 0; i < tab.Length; i++)
{
var value = tab[i];
// use value ...
}
Or, you can also use foreach:
foreach(int value in tab)
{
// use value ...
}
answered Jan 30, 2014 at 8:55
![]()
MarkusMarkus
20.5k4 gold badges29 silver badges53 bronze badges
Your different i values are : tab[0], tab[1], tab[2], tab[3], tab[4].
Then when you call tab[i] you actually call tab[tab[x]]. With x being successively 0, 1, 2, 3, 4. Then if any of your tab value is not in the interval [0, 4], for example 12, you try to reach tab[12] and IndexOutOFRangeException is thrown.
It is certainly where the mistake is if you want to simply loop through your array.
The two correct way to do it are with a for loop :
for (int i = 0; i < tab.Length; i++)
{
// Your code here
}
or with a foreach loop :
foreach(int i in tab)
{
// Your code here
}
answered Jan 30, 2014 at 8:59
if u enter like that…u can get the bound error in html array:
here the error happened in name
<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"+@i, new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID"[@i], @disabled="disabled" })</td>
instead of that:use like that
<td style="width:10%"> @Html.DropDownList("InvoiceUnitID_"+@i, new SelectList(ViewBag.UnitOfMeasures, "Value", "Text", @Model.salesInvoiceVMList[i].InvoiceUnitID), htmlAttributes: new { id = "InvoiceUnitId", name = "InvoiceUnitID[@i]", @disabled="disabled" })</td>
answered Sep 8, 2015 at 11:10
Deepan RajDeepan Raj
1943 silver badges11 bronze badges
- Remove From My Forums
-
Question
-
User-501297529 posted
Get this error on a Submit button click event
How do I fix this?
protected void btnSumbit_Click(object sender, EventArgs e) { if (cboEmployees.SelectedIndex == 0 || cboForeman.SelectedIndex == 0 || cboOSA.SelectedIndex == 0) { lblInformation.Text = "Please make sure that all necessary fields are filled out and all hours entered are numeric"; return; } if (string.IsNullOrEmpty(txtDate.Text) || string.IsNullOrEmpty(txtJobNumber.Text) || string.IsNullOrEmpty(txtContractHours.Text) || string.IsNullOrEmpty(txtRainHours.Text) || string.IsNullOrEmpty(txtOtherHours.Text)) { lblInformation.Text = "Please make sure that all necessary fields are filled out and all hours entered are numeric"; return; } double d; if (!double.TryParse(txtContractHours.Text, out d) || !double.TryParse(txtOtherHours.Text, out d) || !double.TryParse(txtRainHours.Text, out d)) { lblInformation.Text = "Please make sure that all necessary fields are filled out and all hours entered are numeric"; return; } DateTime dt; if (!DateTime.TryParse(txtDate.Text, out dt)) { lblInformation.Text = "Please make sure that all necessary fields are filled out and all hours entered are numeric"; return; } string[] array = cboEmployees.Text.Split(','); EmployeeHours hours = new EmployeeHours(); hours.JobNumber = txtJobNumber.Text; hours.ContractHours = double.Parse(txtContractHours.Text); hours.MillerHours = double.Parse(txtRainHours.Text); hours.TravelHours = double.Parse(txtOtherHours.Text); hours.TimeCardDate = txtDate.Text; PayrollManager payrollManager = new PayrollManager(DateTime.MinValue, DateTime.MinValue, array[1], array[0]); //payrollManager.ProcessNewPayrollEntry(Int64.Parse(cboEmployees.SelectedValue), hours, cboOtherReasons.Text, txtNotes.Text, cboForeman.Text, cboOSA.Text, txtAltJobNumber.Text); GetFromViewStateToSaveToSession(); Response.Redirect("~/Payroll.aspx"); }
Answers
-
User753101303 posted
Hi,
Most often when an item is selected inside a drop down you want to process the «id» of the selected item, not the text shown to the user. So I would change later code to deal with an employee id rather than with an employee name.
Now the confusing part is that the Text property of a DropDown returns actually the Value (not the Text) for the selected item. This is because for most if not all web controls, the Text property is whatever is posted back to the web server (a dropdown renders
an HTML «select» tag, the value posted back to the server is the «value» attribute of the selected option:
https://www.w3schools.com/tags/tag_select.asp).-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User475983607 posted
bootzilla
That line is what is causing the error but when I hover over .Text it shows the employee id which I posted a screen shot of in this thread. I can’t change that dropdown to show the id it has to show the last name, first name. Is there a way to get around
that error? There has to be. That’s what I need help with.Well, this line of code gets the selected text of a dropdownlist.
cboEmployees.TextIf the selected text is a number and you expect a «lastname, fistname» then there is a problem populating the dropdown.
If you are using a 3rd party control then you’ll need to consult the docs for the control as what you’re stated here is confusing. However, the id is what you want, IMHO, not the name. As stated above names are NOT unique.
Change the PayrollManager() method to take the ID as a parameter not the first and last name.
-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
Узнай цену своей работы
Формулировка задачи:
Код к задаче: «19: Ошибка времени выполнения: System.IndexOutOfRangeException: Индекс находился вне границ массива. Стек:»
textual
Листинг программы
while L<r<span class="sy3">-1 do</r<span>
Полезно ли:
9 голосов , оценка 4.222 из 5
Похожие ответы
- Ошибка времени выполнения: Индекс находился вне границ массива
- Ошибка времени выполнения: Индекс находился вне границ массива
- Ошибка времени выполнения: «Индекс находился вне границ массива»
- Ошибка времени выполнения: Индекс находился вне границ массива
- Ошибка времени выполнения: Индекс находится вне границ массива
- Ошибка времени выполнения: Индекс находился вне границ массива
- Ошибка времени выполнения: Индекс находился вне границ массива
- Ошибка времени выполнения: Индекс находился вне границ массива
- Ошибка времени выполнения: Индекс находился вне границ массива
- Ошибка времени выполнения: Индекс находился вне границ массива
- Ошибка времени выполнения: Индекс находился вне границ массива
Improve Article
Save Article
Improve Article
Save Article
C# supports the creation and manipulation of arrays, as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the C# throws an System.IndexOutOfRange Exception. This is unlike C/C++ where no index of the bound check is done. The IndexOutOfRangeException is a Runtime Exception thrown only at runtime. The C# Compiler does not check for this error during the compilation of a program.
Example:
using System;
public class GFG {
public static void Main(String[] args)
{
int[] ar = {1, 2, 3, 4, 5};
for (int i = 0; i <= ar.Length; i++)
Console.WriteLine(ar[i]);
}
}
Runtime Error:
Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at GFG.Main (System.String[] args) <0x40bdbd50 + 0x00067> in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at GFG.Main (System.String[] args) <0x40bdbd50 + 0x00067> in :0
Output:
1 2 3 4 5
Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum value of index can be 4 but in our program, it is going till 5 and thus the exception.
Let’s see another example using ArrayList:
using System;
using System.Collections;
public class GFG {
public static void Main(String[] args)
{
ArrayList lis = new ArrayList();
lis.Add("Geeks");
lis.Add("GFG");
Console.WriteLine(lis[2]);
}
}
Runtime Error: Here error is a bit more informative than the previous one as follows:
Unhandled Exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item (Int32 index) <0x7f2d36b2ff40 + 0x00082> in :0
at GFG.Main (System.String[] args) <0x41b9fd50 + 0x0008b> in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item (Int32 index) <0x7f2d36b2ff40 + 0x00082> in :0
at GFG.Main (System.String[] args) <0x41b9fd50 + 0x0008b> in :0
Lets understand it in a bit of detail:
- Index here defines the index we are trying to access.
- The size gives us information of the size of the list.
- Since size is 2, the last index we can access is (2-1)=1, and thus the exception
The correct way to access array is :
for (int i = 0; i < ar.Length; i++)
{
}
Handling the Exception:
- Use for-each loop: This automatically handles indices while accessing the elements of an array.
- Syntax:
for(int variable_name in array_variable) { // loop body }
- Syntax:
- Use Try-Catch: Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, C# won’t let you access an invalid index and will definitely throw an IndexOutOfRangeException. However, we should be careful inside the block of the catch statement, because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application.
Problem
A calculation fails with the «System.IndexOutOfRangeException: Index was outside the bounds of the array.» exception
Symptom
An inner exception will appear:
Varicent.Core.Exceptions.CalculationFailedException: Calculation failed at ‘example’ —> System.IndexOutOfRangeException: Index was outside the bounds of the array.
at SparkService.CosDataReader.GetValueWithoutExtraQuotes(Int32 i)
at Varicent.Data.Calculations.SubTasks.Mathematical.ClassicComputer.ReadCurrentPartition(IDataReader rdr)
at Varicent.Data.Calculations.SubTasks.Mathematical.ClassicComputer.ComputeRows(IDataReader rdr)
at Varicent.Data.Calculations.SubTasks.Mathematical.SparkClassicComputer.ComputeCsvClassicCalcs(Boolean streamFromCos)
at Varicent.Data.Calculations.SubTasks.Mathematical.ClassicEvaluationSubTask.Output(ClassicQuery query, Boolean hasTrace, Int32 readCount, IProgressTracker tracker, IEvaluationContext context, ISqlStream cmds)
Cause
The calculation is unaggregated and it needs to follow best practices.
Diagnosing The Problem
Investigate the calculation that is in the error message by editing it. Go to the last step of the calculation wizard and check the formula.
Resolving The Problem
By adding a MAX(*) or SUM() operator to the formula and aggregating it, it should fix it.
Document Location
Worldwide
[{«Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Product»:{«code»:»SSGKS6″,»label»:»Cognos Incentive Compensation Management»},»Component»:»»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»All Versions»,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]