I have the following method I’m working on:
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;
}
}
This works fine with the exception of Directory.GetDirectories() and Directory.GetFiles() can both throw exceptions that I want to catch.
I can’t catch the pieces of code which utilize those methods due to my use of yield (yields can’t be placed within the body of a try if there is a catch). I know I could remove the yield and simply add to my children to a collection but I’m curious how someone would catch IOExceptions from both of those methods and still utilize yield?
How about something like (for the first part):
And similarly for the second. You don’t need to yield within that try block. If this doesn’t help, please write whatever code you would want to be valid, so that we can see what you’re planning to do if an exception is thrown.