Neomex
Neomex

Reputation: 1660

Value out of array bounds

I am iterating throu array and sometimes I have to check values that exceed the boundary. Of course it throws exception, but I don't want to completly stop application after it, just skip this element of code.

Is something like this safe and won't cause memory leaks?

try
{
    if (arrayName[i - 1, j].DoSomething())
         something++;
}
catch
{ // empty for purpose
}

Upvotes: 0

Views: 5628

Answers (4)

Will Vousden
Will Vousden

Reputation: 33358

It won't cause memory leaks, as long as you're not allocating resources in the try block in such a way that an exception causes them not to be released (usually via a Dispose method). If this is the case, consider using a using block to guarantee that resources are released.

It's somewhat unclear what you're trying to do, but it seems like you're trying to use exceptions as a mechanism for avoiding checking explicitly whether your array indices are valid. This is (usually) a bad thing, since exceptions should be used for exceptional circumstances that you don't expect to happen if the input is sensible and for which there's no reasonable way of preventing it. If you provide a bit more context, we may be able to suggest a better way of doing it.

Also, as kfugslang says, you should almost always avoid using empty and unqualified catch blocks, since these will catch any exception that occurs in the try block, not just the one you're expecting to be thrown. For example, some internal method further down the stack might throw a completely unrelated exception that has nothing to do with your own code and it'd just be swallowed. You'd be none the wiser, but the results would be unpredictable and most likely incorrect.

Instead, you should try only to use qualified catch statements for particular exception types.

Upvotes: 1

Jason
Jason

Reputation: 15931

i would check to make sure the position in the array is valid

if (arrayName[i - 1, j] != null) 
{
  arrayName[i - 1, j].DoSomething();
}

or use the try/catch, but log it, so it's not lost forever.

try
{
    if (arrayName[i - 1, j].DoSomething())
         something++;
}
catch(Exception e)
{ 
    _log.Error(e.Message);
}

regardless, the approach you outlined, while not a best practice, won't cause memory leaks

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292405

Just check that the indexes are in range. GetLength returns the length of the specified dimension:

if (i - 1 < arrayName.GetLength(0) && j < arrayName.GetLength(1))
{
    if (arrayName[i - 1, j].DoSomething())
        something++;
}

Upvotes: 1

kfuglsang
kfuglsang

Reputation: 2505

It is much better practice to use an if-statement or the like, rather than swallowing exceptions.

You can check a further discussion on the topic here: Why are empty catch blocks a bad idea?

Upvotes: 6

Related Questions