c# - How do I use try-catch correctly in simple methods? -
i make sure classes robust - if simple , seem dumb experienced programmer.
let's have method written below accepts string[] , returns int[].
public static int[] getintarrayfromstringarray(string[] stringarray) { int = 0; int[] ints = new int[stringarray.length]; foreach (var str in stringarray) { ints[i++] = (str != "" ? int.parse(str) : 0); } return ints; } is best option use try-catch , throw exception? when try use try-catch, seems have issues variables not being in scope need them in try-catch catch errors stringarray being null!
perhaps should use this?
if (stringarray == null) //do ... but not sure in event of error ... return null int[] or throw exception?
(i have check int.parse(str) doesn't fail - i'm getting 1 hoped in try-catch block!)
as said, these simple tasks want try , correct before develop many bad habits. thanks.
public static int[] getintarrayfromstringarray(string[] stringarray) { if (stringarray == null) { throw new argumentnullexception("stringarray"); } int count = stringarray.length; int[] ints = new int[count]; (int = 0; < count; i++) { int intvalue; ints[i] = int.tryparse(stringarray[i], out intvalue) ? intvalue : 0; } return ints; }
Comments
Post a Comment