© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
12 replies
engineertdog

Uncaught exception

I have the following code as part of a class I'm building for impersonation. It works, but the UnauthorizedAccessException is being marked as unhandled. If I hit continue, it all works as expected. But why is it unhandled and how can I address that?

try {
  WindowsIdentity.RunImpersonated(_safeAccessTokenHandle, () => {
    // This will throw if the impersonation fails
    //string impersonatedUser = WindowsIdentity.GetCurrent().Name;
    //Console.WriteLine("Impersonation successful, current user: " + impersonatedUser);

    try {
      string securePath = "";
      if (!Directory.Exists(securePath)) {
        throw new UnauthorizedAccessException($"Access to {securePath} was denied.");
      }
    } catch {
      throw;
    }
  });
} catch (Exception ex) {
  Console.WriteLine($"Impersonation validation failed: {ex.Message}");
  Dispose();
  // Re-throw to ensure the exception is handled by the caller
  throw;
}
try {
  WindowsIdentity.RunImpersonated(_safeAccessTokenHandle, () => {
    // This will throw if the impersonation fails
    //string impersonatedUser = WindowsIdentity.GetCurrent().Name;
    //Console.WriteLine("Impersonation successful, current user: " + impersonatedUser);

    try {
      string securePath = "";
      if (!Directory.Exists(securePath)) {
        throw new UnauthorizedAccessException($"Access to {securePath} was denied.");
      }
    } catch {
      throw;
    }
  });
} catch (Exception ex) {
  Console.WriteLine($"Impersonation validation failed: {ex.Message}");
  Dispose();
  // Re-throw to ensure the exception is handled by the caller
  throw;
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Uncaught Exception C++ hostfxr Handling
C#CC# / help
4y ago
✅ GetGlobalApplicationCommandsAsync exception
C#CC# / help
2y ago
✅ Exception handling..
C#CC# / help
17mo ago
✅ Exception handling
C#CC# / help
17mo ago