Exception error in Visual Basic 2013 - c#

I try to run code using C# from http://dynamicnotions.blogspot.com/2008/09/training-neural-networks-using-back.html but it give an error while running and give this message
An unhandled exception of type 'System.Exception' occurred.
I have try fix the error but another error will appear. Can anybody help me find the problem occurred in this code?
public Pattern(string value, int inputSize)
{
string[] line = value.Split(',');
if (line.Length - 1 != inputSize)
throw new Exception("Input does not match network configuration"); //error occur
_inputs = new double[inputSize];
for (int i = 0; i < inputSize; i++)
{
_inputs[i] = double.Parse(line[i]);
}
_output = double.Parse(line[inputSize]);
}

The only way I see for a System.Exception to be thrown is from the lines:
if (line.Length - 1 != inputSize)
throw new Exception("Input does not match network configuration"); //error occur
This probably means that the number of columns you say you have in your CSV int inputSize does not match the number of columns actually found in value by splitting on comma characters.
string[] line = value.Split(',');
Check your CSV file to make sure it has the same number of columns that you specify.
Note too that commas in the data itself, if not properly handled, can throw this off. For example, if you have a CSV with columns FirstName and LastName, adding "John,Smith,Jr" will make it seem like there's an extra column.

Related

C# Is there "Ternary-style" Exception Handling?

I sometimes run into situations where, if a line of code throws an exception, I don't care what the exception is or why it was thrown; I just need to take a generic action and move on. For example:
try
{
// Throws IndexOutOfRangeException when DB field
// is null in the current record
Template = record.GetString(MYSQL_IDX_TEMPLATE);
}
catch
{
Template = FIELD_UNAVAILABLE;
}
I was wondering if there's a short-hand way to set a value based on a generic try/catch?
I'm thinking of something similar to ternary syntax:
string blah = (index >= ubound ? "No more records" : "records exist");

Adding items from a text file to an array

In my C# program, I'm trying to read in data from a text file to an array. I've looked at many answers on here and can't figure out what's wrong with my code. Whenever I run it, I get an exception that says that I got an unhandled exception of type 'System.IndexOutOfRangeException', but I don't understand why the index would be out of range.
Here's what I have:
string[] namesArray = new string[] { };
using (var sr = new StreamReader(mydocpath + #"\nameIDLines.txt"))
{
for (int i = 1; i < numLines; i++)
{
nameIDLine = sr.ReadLine();
nameIDLine = nameIDLine.Split(new string[] { "ID" }, StringSplitOptions.None)[0];
namesArray[i] = nameIDLine;
}
}
When you do this:
string[] namesArray = new string[] { };
You're initializing an array with length 0. Therefore, when you do namesArray[i], it will always be out of range regardless of i.
Since you know the number of lines, and therefore the number of items, you can initialize the array with that number:
string[] namesArray = new string[numLines];
As #stybl pointed out, the problem is that you are initializing a zero-length array to store your lines... and that will always lead to an "index out of range" exception. On the top of that, I wonder how you are managing to get a consistent numLines value while using a StreamReader to parse the file... this is very risky since you must be sure that the file always contains enough lines.
I suggest you to use the following approach instead:
String[] lines = File.ReadAllLines(mydocpath + #"\nameIDLines.txt");
If you want to take a specific number of lines from the file, you can proceed as follows:
String[] lines = File.ReadAllLines(mydocpath + #"\nameIDLines.txt").Take(numLines).ToArray();

Exception Occurred

I'm constantly getting the same error.
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: InvalidArgument=Value of '0' is not valid for 'index'.
The Code is:
private void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)
{
if (e.CellElement.ColumnInfo.HeaderText == "logo")
{
if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Error")
{
e.CellElement.Image = (Image)imageList1.Images[0];
e.CellElement.ToolTipText = "Error";
}
else if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Warning")
{
e.CellElement.Image = imageList1.Images[1];
e.CellElement.ToolTipText = "Warning";
}
else if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Message")
{
e.CellElement.Image = imageList1.Images[2];
e.CellElement.ToolTipText = "Message";
}
}
}
}
//-----------------------------------------------------------------------
MSDN says this
The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
about the ArgumentOutOfRangeException. It goes on to say that
You are retrieving the member of a collection by its index number, and the index number is invalid.
This is the most common cause of an ArgumentOutOfRangeException
exception. Typically, the index number is invalid for one of three
reasons:
The collection has no members, and your code assumes that it does.
You're attempting to retrieve an item whose index is negative. This
usually occurs because you've searched a collection for the index of a
particular element and have erroneously assumed that the search is
successful.
You're attempting to retrieve an element whose index is equal to the
value of the collection's Count property.
My suspicion is that it's the first case here, i.e. imageList1 is empty. So your imageList1.Images[0] throws the exception because there is nothing there.
To determine if this is the case try imageList1.Images.Count. Given you're looking at 3 elements in your code Count must be >= 3.
From the looks of it, you don't have anything in the array. Do a check to see if the indices are actually initialized, and then go on from there.

'System.FormatException' occurred in mscorlib.dll but was not handled in user code

The code works fine when I added the first row, but then afterwards it throws me
An exception of type System.FormatException occurred in mscorlib.dll but was not handled in user code
I've been staring at this code for quite a while now and cant seem to pinpoint what's the issue that could cause this.
protected void OnAddEmployee(object sender, EventArgs e)
{
if (gridViewPersonal.SelectedDataKey == null)
{
return;
}
int employeeID = 0;
foreach (GridViewRow row in gridViewEmployee.Rows)
{
if (employeeID < int.Parse(row.Cells[0].ToString()))
{
employeeID = int.Parse(row.Cells[0].ToString());
}
}
employeeID++;
cmd.ExecuteNonQuery();
con.Close();
}
}
As I mentioned in the comment, the issue is with the conversion, Please take a look into the foreach, There you are getting the value of row.Cells[0].ToString() sometimes that is null, empty or some other values which are not convertible to a valid integer, this time you will get FormatException as you are getting now. One more thing you are doing wrong there, you are parsing the same value two times, to avoid both of these mistakes you can use TryParse, in this case your code will be like this:
int employeeID = 0;
foreach (GridViewRow row in gridViewEmployee.Rows)
{
if (int.TryParse(row.Cells[0].ToString(), out employeeID))
{
break;
}
}
Please note : I just tried to give you an example usage of int.TryParse inside that loop, I don't get the exact process that you are tried with the loop here, In the above example if will break the loop when the first valid conversion executes. you can remove the break if you want to loop through all the rows.
That error occurs when int.parse runs into non-numeric characters. You could use a try catch block to catch the error and just move onto the next row or you could use int.tryparse to check it as you go without the try catch. Here's code with the tryparse:
int employeeID = 0;
foreach (GridViewRow row in gridViewEmployee.Rows)
{
string curStr = row.Cells[0].ToString();
int curID = 0;
if (int.TryParse(curStr, curID)){
if (employeeID < curID)
{
employeeID = curID);
}
}
}
employeeID++;
You should probably also use a debugger to step through and observe the cell value as a string before parsing it, which is why I made a separate variable for it. I hit myself over the head hardest (figuratively) when I finally realize that I have been pulling data from the wrong column the whole time.

"IndexOutOfRangeException: Index was outside of the array." exception occured

I encountered this exception while setting the SetKeyName method of ImageCollection of ImageList.
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Fuchsia;
this.imageList1.Images.SetKeyName(0, "");
this.imageList1.Images.SetKeyName(1, "");
i have used this "imageList1.ImageStream" in my Main Form too, and it works fine there. I am stuck here and i do not know what actually this issue is, how it raised and how can i solve this.
Any suggestions and comments will be much appreciated. Thank you!!
Try this:
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Fuchsia;
for (int i = 0; i < this.imageList1.Images.Count; i++)
this.imageList1.Images.SetKeyName(i, "");
Most likely this line :
this.imageList1.Images.SetKeyName(1, "");
Is causing your exception. Of course it could also be the first line with Index 0. Basically the exception is saying that code failed while trying to access the array at a given index. The reason being that the array doesn't have an item at that index.
For example in your case the code assumes that there are 2 items in the array. One at index 0 and one at index 1. If the array has only one item the second line will fail and throw the exception.
All you have to do is make sure you have an item at a given index before you try to perform any operations on it.
Something like :
if(this.imageList1.Images.Count >= 2)
{
this.imageList1.Images.SetKeyName(1, "");
}

Categories

Resources