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();
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();
} 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?