title: How to return Func(Of T, IEnumerable(Of T)) inside a function which handles the exception?
body: <p>How can I handle the following exception?</p>
  <p><strong>My code:</strong></p>
  <pre><code>Public Module RecursiveEnumerableExtensions
      'credits Eric Lippert https://stackoverflow.com/users/88656/eric-lippert
      Iterator Function Traverse(Of T)(ByVal root As T, ByVal children As Func(Of T, IEnumerable(Of T)), ByVal Optional includeSelf As Boolean = True) As IEnumerable(Of T)
          If includeSelf Then Yield root
          Dim stack = New Stack(Of IEnumerator(Of T))()
          Try
              stack.Push(children(root).GetEnumerator())
              While stack.Count &lt;&gt; 0
                  Dim enumerator = stack.Peek()
                  If Not enumerator.MoveNext() Then
                      stack.Pop()
                      enumerator.Dispose()
                  Else
                      Yield enumerator.Current
                      stack.Push(children(enumerator.Current).GetEnumerator())
                  End If
              End While
          Finally
              For Each enumerator In stack
                  enumerator.Dispose()
              Next
          End Try
      End Function
  End Module
  
  Friend Sub Main()
      Dim dinfo As DirectoryInfo = New DirectoryInfo(curDirectory)
      Dim dquery = RecursiveEnumerableExtensions.Traverse(dinfo, Function(d) d.GetDirectories())
  End Sub
  </code></pre>
  <p>When I run my code, for some of the directories, which are not accessible, I receive inside the <code>Friend Sub Main()</code> in the part <code>Function(d) d.GetDirectories())</code> the exception <code>System.UnauthorizedAccessException</code>. I would like to handle this by <code>Try Catch</code>.</p>
  <p>I tried to edit the <code>Friend Sub Main()</code> and export the Lambda expression to a function <code>funcGetDirectories</code>, but it fails with following error: <code>System.InvalidCastException</code></p>
  <pre><code>Friend Sub Main()
      Dim dinfo As DirectoryInfo = New DirectoryInfo(curDirectory)
      Dim dquery = RecursiveEnumerableExtensions.Traverse(dinfo, funcGetDirectories(dinfo))
  End Sub
  
  Function funcGetDirectories(di As DirectoryInfo)
      Try
          Return di.GetDirectories()
      Catch ex As UnauthorizedAccessException
          Throw
      Catch ex_default As Exception
          Throw
      End Try
  End Function
  </code></pre>
  <p>Whats wrong with my <code>Return di.GetDirectories()</code>?</p>
  <p>Note I'm working with .NET 4.8.</p>