如何在C#中产生并捕获必要的异常?

mmc*_*ole 1 .net c# yield try-catch

我正在研究以下方法:

    private IEnumerable<TreeNode> GetChildNodes(TreeNode parent)
    {
        string path = parent.Tag.ToString();

        // Add Directories
        string[] subdirs = Directory.GetDirectories(path);

        foreach (string subdir in subdirs)
        {
            yield return GetChildNode(subdir);
        }

        // Add Files
        string[] files = Directory.GetFiles(path);

        foreach (string file in files)
        {
            var child = GetChildNode(file);
            fileNodeMap[file] = child;
            yield return child;
        }
    }
Run Code Online (Sandbox Code Playgroud)

除了Directory.GetDirectories()和Directory.GetFiles()都可以抛出我想要捕获的异常,这样可以正常工作.

由于我使用了yield,我无法捕获利用这些方法的代码片段(如果有一个catch,则不能将yield放在try的主体内).我知道我可以删除收益并简单地将我的孩子添加到一个集合中,但我很好奇有人会从这两种方法中捕获IOExceptions并仍然使用yield?

Jon*_*eet 5

怎么样(第一部分):

string[] subdirs;
try
{
    subdirs = Directory.GetDirectories(path);
}
catch (IOException e)
{
    // Do whatever you need here
    subdirs = new string[0];
}
Run Code Online (Sandbox Code Playgroud)

第二个类似.您不需要在该try块内屈服.如果这没有帮助,请写下您希望有效的任何代码,以便我们可以看到如果抛出异常您打算做什么.