I would like to make sure my classes are robust – even if they are simple and seem dumb to an experienced programmer.
Let’s say I have a method as written below that accepts a string[] and returns it as an int[].
public static int[] GetIntArrayFromStringArray(string[] stringArray)
{
int i = 0;
int[] ints = new int[stringArray.Length];
foreach (var str in stringArray)
{
ints[i++] = (str != "" ? int.Parse(str) : 0);
}
return ints;
}
Is the best option to use try-catch and throw an exception? When I try to use try-catch, it seems to have issues with my variables not being in scope but I need them to be in a try-catch to catch any errors with the stringArray being null!
Perhaps I should use this?
if (stringArray == null) //do something ...
but not sure what to do in the event of an error … do I return a null int[] or throw exception?
(I also have to check that the int.Parse(str) doesn’t fail – I’m getting to that one but hoped it could be in the try-catch block!)
As I said, these are simple tasks that I want to try and get correct now before I develop too many bad habits. Thanks.
1 Answer