{"record":{"id":"118d15b9575e9a3e","repo":"dotnet/wpf","slug":"e-unexpected","errorCode":"E_UNEXPECTED","errorMessage":"ElementNotAvailableException(e)","messagePattern":"ElementNotAvailableException\\(e\\)","errorType":"exception","errorClass":"ElementNotAvailableException","httpStatus":null,"severity":"warning","filePath":"src/Microsoft.DotNet.Wpf/src/UIAutomation/UIAutomationClientSideProviders/MS/Internal/AutomationProxies/Accessible.cs","lineNumber":1366,"sourceCode":"                        // GetWindowThreadProcessID fails and it therefore won't be able to allocate shared\n                        // memory in the target process, so it incorrectly assumes OOM.\n                        throw new ElementNotAvailableException(e);\n                        \n                    case NativeMethods.E_INVALIDARG:\n                        // One or more arguments were invalid. This error occurs when the caller attempts to identify\n                        // a child object using an identifier that the server does not recognize. This error also results\n                        // when a client attempts to identify a child object within an object that has no children.\n                        throw new ArgumentException(SR.InvalidParameter);\n\n                    case NativeMethods.E_ACCESSDENIED:\n                        // This is returned when you call get_accValue to get the value of a password control.\n                        throw new UnauthorizedAccessException();\n\n                    case NativeMethods.E_UNEXPECTED:\n                        // An IAccessible server has been released unexpectedly but still has pending events.\n                        // If the current execution context is inside one of these event handlers it must be \n                        // abandoned.\n                        throw new ElementNotAvailableException(e);\n\n                    default:\n                        // we want to know when we get an exception we haven't seen before\n                        Debug.Fail(string.Format(CultureInfo.CurrentCulture, \"MsaaNativeProvider: IAccessible threw a COMException: {0}\", e.Message));\n                        break;\n                }\n            }\n            else if (e is InvalidCastException)\n            {\n                // sometimes Trident throws InvalidCastExceptions on elements from obsolete pages\n                throw new ElementNotAvailableException(e);\n            }\n            else if (e is BadImageFormatException)\n            {\n                // This control/window mostly has went away or is in the process of shutting down.\n                throw new ElementNotAvailableException(e);\n            }\n            else","sourceCodeStart":1348,"sourceCodeEnd":1384,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/UIAutomation/UIAutomationClientSideProviders/MS/Internal/AutomationProxies/Accessible.cs#L1348-L1384","documentation":"The IAccessible server returned E_UNEXPECTED and the provider translates it into ElementNotAvailableException. Per the code comment this means the MSAA server was released unexpectedly but still has pending events; if execution is inside one of the provider's event handlers it must be abandoned. It signals the accessible server object died mid-operation.","triggerScenarios":"An Accessible-wrapped IAccessible call (property read, navigation, or an event handler callback on the provider) after the native server was released — e.g. the hosting window/control was destroyed while MSAA events were still being dispatched.","commonSituations":"Applications closing windows during active AutomationEventHandler/AutomationFocusChanged callbacks; UIA clients holding AutomationEventHandlers registered on short-lived windows; crash or fast exit of the target app during event dispatch.","solutions":["Catch ElementNotAvailableException in event handlers and exit the handler gracefully (the framework requires abandoning the context).","Unregister event handlers (RemoveAutomationEventHandler) when the target window is closed rather than leaving them attached.","Check whether the target application is crashing or leaking COM references; use AppVerifier/COM ref tracking if the server release is unexpected.","Retry the operation after re-resolving the element tree; the element that owned the server is gone."],"exampleFix":"// before\nAutomation.AddAutomationEventHandler(InvokePattern.InvokedEvent, win, TreeScope.Element,\n    (s, e) => Process(e.Source.Current.Name)); // server released -> E_UNEXPECTED crash out of handler\n// after\nAutomation.AddAutomationEventHandler(InvokePattern.InvokedEvent, win, TreeScope.Element,\n    (s, e) =>\n    {\n        try { Process(e.Source.Current.Name); }\n        catch (ElementNotAvailableException) { /* server released; abandon handler */ }\n    });","handlingStrategy":"try-catch","validationCode":"// Before relying on long-lived event subscriptions, confirm the target window is open:\nbool TargetAlive(Process p) => !p.HasExited && p.MainWindowHandle != IntPtr.Zero;","typeGuard":null,"tryCatchPattern":"try\n{\n    HandleEvent(e);\n}\ncatch (ElementNotAvailableException)\n{\n    // server released with pending events: abandon this handler invocation\n    return;\n}","preventionTips":["Wrap all UIA event-handler bodies in try/catch for ElementNotAvailableException.","Remove event handlers when the owning window closes instead of leaving them attached.","Watch for target-app crashes or leaked COM references causing premature server release.","Re-resolve elements after catching; the old backing IAccessible is permanently gone."],"tags":["uiautomation","wpf","msaa","com-lifetime","event-handler"],"backgroundTag":"stale-ui-automation-element","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}