Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling a null exception C#

Tags:

c#

null

Ok, new coder here looking for a little insight into this problem. So I have a for loop like that starts like this:

for (int i = 0; i < rowHandles.Length; i++)
{
      .........code....
}

rowHandles is an int array that contains rows of data. This for loop has code that deletes the rows of data when a delete button is clicked, to be specific it is a grid tool strip Delete button and this is inside the delete button click event handler. The problem is the delete button can be clicked when there are no rows left, so rowHandles.Length is equal to null. How would I prevent this from stopping the program? Is there something I could add inside the for loop, in the for loop declaration, or outside the for loop to correct this? Maybe a try catch? How would this be structured around this specific problem/loop?

Thanks for all your help - Newbie Coder

like image 587
Nard Dog Avatar asked Oct 29 '10 19:10

Nard Dog


People also ask

How do you catch null reference exception?

Being a plain old C# exception, NullReferenceException can be caught using a try/catch : try { string s = null; s. ToString(); } catch (NullReferenceException e) { // Do something with e, please. }

Should you throw null reference exception?

Handling NullReferenceException in release codeIt's usually better to avoid a NullReferenceException than to handle it after it occurs. Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. A NullReferenceException is often a non-recoverable error.

How do I fix NullReferenceException object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.


1 Answers

If the problem is that rowHandles can be null then just add an explicit check for that which prevents you from executing the for statement.

if ( rowHandles != null ) { 
  for ( int i = 0; i < rowHandles.Length; i++ ) {
    ...
  }
}

Another option would be to disable the delete button altogether if there are no rows to be deleted. The operation is invalid so prevent it from the start.

like image 185
JaredPar Avatar answered Sep 28 '22 05:09

JaredPar