Why is the exception from the thrown code not caught?

My C # code uses impersonation by calling Win32 functions through P / Invoke

internal class Win32Native
{
    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern int ImpersonateLoggedOnUser(IntPtr token);

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern int RevertToSelf();
}

try {
    var token = obtainTokenFromLogonUser();
    Win32Native.ImpersonateLoggedOnUser( token );
    throw new Exception(); // this is for simulation
    Win32Native.RevertToSelf()
} catch( Exception e ) {
    LogException( e );
    throw;
}

I also have a handler installed AppDomain.CurrentDomain.UnhandledExceptionthat also logs all unhandled exceptions.

I am sure that the code that logs exceptions works great with and without impersonation.

Now the problem is that in the above code it looks like it is catchnot being entered, nor is UnhandledExceptionit being called. The only consequence of the exception is the entry in the event viewer.

If I add finallyas follows:

try {
    var token = obtainTokenFromLogonUser();
    Win32Native.ImpersonateLoggedOnUser( token );
    try {
       throw new Exception(); // this is for simulation
    } finally {
        Win32Native.RevertToSelf()
    }
} catch( Exception e ) {
    LogException( e );
    throw;
}

then the exception is written in order from both the catchhandler and the handler UnhandledException.

What's happening? Does an executing thread throw an exception to normal exception handling?

+5
2

LogException, , , , , -/loggedon , , .., . , , " ", , .

, , , , LogException - , .

, LogException "", , , .

+3

, . - , (Process.StartTime), Access denied .

Access is denied
System.ComponentModel.Win32Exception
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.GetProcessTimes()
at System.Diagnostics.Process.get_StartTime()
//our logging code here

, System.Diagnostics.Trace.WriteLine() Process.StartTime, " " , .

, . , , . .

+1

All Articles