假设您正在调用类似于以下的方法,您知道该方法只会引发 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)
您将使用以下哪项来调用方法并处理异常:
方法一(先检查输入参数)
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");
}
}
多年来,我已经教授了这两种方法,并且想知道这种情况下的一般最佳实践是什么。
更新
一些海报关注的是抛出异常的方法,而不是处理这些异常的方式,所以我提供了一个.Net Framework 方法的示例,它的行为方式相同(Membership.GetUser (String))所以,为了澄清我的问题,如果我们打电话给您,您将Membership.GetUser(input)
如何处理可能的异常,方法 1、2 或其他方法?
谢谢