说你打电话类似如下,你知道的方法只有永远要扔的2个例外之一:最佳实践
public static void ExceptionDemo(string input)
{
if (input == null)
throw new ArgumentNullException("input");
if (input.Contains(","))
throw new ArgumentException("input cannot contain the comma character");
// ...
// ... Some really impressive code here
// ...
}
方法的一个活生生的例子这不,这是Membership.GetUser (String)
你会用下列哪调用的方法和处理异常:
方法1(检查输入参数第一首)
public static void Example1(string input)
{
// validate the input first and make sure that the exceptions could never occur
// no [try/catch] required
if (input != null && !input.Contains(","))
{
ExceptionDemo(input);
}
else
{
Console.WriteLine("input cannot be null or contain the comma character");
}
}
方法2(包裹呼叫一个try/catch)
public static void Example2(string input)
{
// try catch block with no validation of the input
try
{
ExceptionDemo(input);
}
catch (ArgumentNullException)
{
Console.WriteLine("input cannot be null");
}
catch (ArgumentException)
{
Console.WriteLine("input cannot contain the comma character");
}
}
我已经教过几年这两种方法,并想知道一般最佳的做法是这种情况。
更新 一些海报注重方法抛出这些异常,正在处理的异常,而不是办法,所以我提供(Membership.GetUser (String)其行为以同样的方式一个.NET Framework方法的一个例子) 因此,为了澄清我的问题,如果您打电话给Membership.GetUser(input)
,您将如何处理可能的例外情况,方法1,2或其他?
感谢
当然方法一例外是昂贵的,在这种情况下,你可以避开他们用一个简单的检查。 –
对于预期的程序行为,不应该发生异常,只是为了例外(这就是为什么他们被称为异常)的情况,而这些情况并不是预期的。 – helb