嵌套的try捕获在这种情况下是合理的

本文关键字:这种情况下 try 嵌套 | 更新日期: 2023-09-27 17:53:44

如果你有一个蛮力搜索,用户不知道数据类型,那么我们可以这样做吗?

        if (search.Length > 0 && comboBox1.Text.Equals("Data Type Not Known"))
        {
            try
            {
                ParentGraph p = new ParentGraph(search);
            }
            catch (NoDataFoundException ndfe)
            {
                //it fails so try different data type
                try
                {
                    CompoundGraph c = new CompoundGraph(search);
                }                
                catch(NoDataFoundException ndfe)
                {
                    //failed so try final type
                    try
                    {
                        BatchGraph b = new BatchGraph(search);
                    }
                    catch(NoDataFoundException ndfe)
                    {
                        MessageBox.Show("Data could not be linked to a particular search")
                    }
                }
            }
        }

嵌套的try捕获在这种情况下是合理的

这将工作,但它是丑陋的在两个方面:

    感觉代码复制是一个坏主意…你是否可以有一个List<T>,例如List<Func<string, object>>,并依次尝试每个工厂代表?
  • 如果找不到数据是合理的,那就不应该是例外。考虑编写工厂方法而不是构造函数,如果没有找到数据则返回null…或者有一个带有out参数和bool返回值的TryGetData(或者可能只是一个元组返回值)。用异常处理这个流程对我来说感觉不对。

除了频繁地抛出异常之外,看起来搜索构造函数可能做了比它应该做的更多的工作。我希望所有实例都使用轻构造函数实例化,然后在调用方法时让它们执行实际工作,例如:

// initialize graph
IGraph p = new ParentGraph();
// get the results (although count may be zero)
IEnumerable<Result> results = p.GetResults(search); // never throws an exception

一个通用的接口看起来像这样:

interface IGraph
{
    IEnumerable<Result> GetResults(string search); 
}

如果你所有的图形实例都实现了IGraph,你可以这样使用它们:

IEnumerable<IGraph> knownGraphs = new IGraph[] 
{
    new ParentGraph(),
    new CompoundGraph(),
    ...
}
// get results from the first graph which can give them
foreach (IGraph graph in knownGraphs)
{
   List<Result> results = graph.GetResults(search).ToList()
   if (results.Count > 0)
      return results;
}