【发布时间】:2013-10-04 18:41:14
【问题描述】:
假设您正在调用类似于以下的方法,您知道该方法只会引发 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 或其他什么?
谢谢
【问题讨论】:
-
Method1 当然异常是昂贵的,在这种情况下你可以通过简单的检查来避免它们。
-
对于预期的程序行为不应发生异常,仅适用于无法预见的异常(这就是它们被称为异常的原因)情况。
标签: c# exception exception-handling