[英]How do I use try-catch correctly in simple methods?
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[]. 假设我有一个如下所示的方法接受字符串[]并将其作为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? 是使用try-catch并抛出异常的最佳选择吗? 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!
当我尝试使用try-catch时,似乎我的变量不在范围内但我需要它们在try-catch中以捕获stringArray为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? 但不确定在发生错误时该怎么办...我是否返回null int []或抛出异常?
(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!) (我还必须检查int.Parse(str)是否没有失败 - 我已经到了那个但是希望它可以在try-catch块中!)
As I said, these are simple tasks that I want to try and get correct now before I develop too many bad habits. 正如我所说,在我养成太多不良习惯之前,这些是我想要尝试并且正确的简单任务。 Thanks.
谢谢。
You can use int.TryParse() instead. 您可以使用int.TryParse()代替。
http://msdn.microsoft.com/en-us/library/f02979c7.aspx http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Try something simpler for the conversion: 尝试更简单的转换:
return stringArray.Select(s => IntParseOrDefault(s, 0)).ToArray(); return stringArray.Select(s => IntParseOrDefault(s,0))。ToArray();
Where IntParseOrDefault is just like this: IntParseOrDefault就是这样的:
int IntParseOrDefault(string s, int defaultVal)
{
int i;
if (!int.TryParse(s, out i)) i = defaultVal;
return i;
}
If you want the method to fail if any of the strings is not a valid integer, then instead of using a default value, throw an InvalidArgumentException when TryParse fails. 如果您希望方法失败,如果任何字符串不是有效整数,那么当TryParse失败时,抛出InvalidArgumentException而不是使用默认值。
Here an example 这是一个例子
foreach (string str in stringArray)
{
int nr = 0;
int.TryParse(str, out nr);
if (nr > 0)
ints[i++] = nr;
}
here is the full code 这是完整的代码
public static int[] GetIntArrayFromStringArray(string[] stringArray)
{
if (stringArray == null || stringArray.Length == 0)
throw new ArgumentNullException("string array is null or empty");
int i = 0;
int[] ints = new int[stringArray.Length];
foreach (var str in stringArray)
{
int nr = 0;
int.TryParse(str, out nr);
if (nr > 0)
ints[i] = nr;
i++;
}
return ints;
}
Here is how you can use try - catch: 以下是如何使用try-catch:
public static int[] GetIntArrayFromStringArray(string[] stringArray)
{
int i = 0;
int[] ints = null;
try {
ints = new int[stringArray.Length];
foreach (var str in stringArray)
{
ints[i++] = (str != "" ? int.Parse(str) : 0);
}
}
catch {
// Throw custom exception
}
return ints;
}
I would throw a custom-exception in the catch-block. 我会在catch块中抛出一个自定义异常。 So the user of your class can catch for this exception.
因此,您的类的用户可以捕获此异常。
public static int[] GetIntArrayFromStringArray(string[] stringArray)
{
int i = 0;
int[] ints;
int num;
if (stringArray == null && stringArray.Length > 0)
{
ints = new int[stringArray.Length]
foreach (var str in stringArray)
{
if (string.IsNullOrEmpty(str) && int.TryParse(str, num))
{
ints[i++] = num;
}
}
}
return ints;
}
public static int[] GetIntArrayFromStringArray(string[] stringArray)
{
if (stringArray == null)
{
throw new ArgumentNullException("stringArray");
}
int count = stringArray.Length;
int[] ints = new int[count];
for (int i = 0; i < count; i++)
{
int intValue;
ints[i] = int.TryParse(stringArray[i], out intValue) ? intValue : 0;
}
return ints;
}
Many methods in the .NET Framework that throw exceptions on invalid input have non-throwing counterparts, usually prefixed with Try
, that return a boolean value instead. .NET Framework中的许多方法在无效输入上抛出异常都有非抛出对应物,通常以
Try
为前缀,它返回一个布尔值。 For instance, in the case of int.Parse
, you'll have an easier time calling int.TryParse
, eg: 例如,在
int.Parse
的情况下,您将更容易调用int.TryParse
,例如:
public static int[] GetIntArrayFromStringArray(string[] stringArray)
{
int i = 0;
int[] ints = new int[stringArray.Length];
foreach (var str in stringArray)
{
int a = 0
int.TryParse(str, out a)
ints[i++] = a;
}
return ints;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.