question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

The Application.UnhandledException does not occur when the exception is thrown inside a Page in WinUI 3 Windows App SDK 0.8.1

See original GitHub issue

Describe the bug This is my MainWindow.xaml.cs:

<Window x:Class="Pixeval.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Closed="MainWindow_OnClosed"
        mc:Ignorable="d">
    <Frame x:Name="PixevalAppRootFrame"
           Loaded="PixevalAppRootFrame_OnLoaded"
           NavigationFailed="PixevalAppRootFrame_OnNavigationFailed" />
</Window>

and code behind:

private void PixevalAppRootFrame_OnLoaded(object sender, RoutedEventArgs e)
{
    PixevalAppRootFrame.Navigate(typeof(LoginPage));
}

private async void MainWindow_OnClosed(object sender, WindowEventArgs args)
{
    await App.ExitWithPushedNotification();
}

private void PixevalAppRootFrame_OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
    e.Handled = true;
    throw e.Exception;
}

so basically it will navigate to LoginPage immediately after the MainWindow is loaded. And I’ve also added an event handler that does nothing but throws an exception in the LoginPage.xaml.cs

private async void LoginPage_OnLoaded(object sender, RoutedEventArgs e)
{
    throw new Exception();
}

According to the document, this exception is thrown from the UI thread thus should be caught by Application.UnhandledException, but the truth is the exception is escaped from the event handler, the visual studio breaks twice, the first time it shows “Unhandled exception at 0x00007FF822ACBD3E (KernelBase.dll) in Pixeval.exe: 0xC000027B: An application-internal exception has occurred (parameters: 0x000001F337CFADA0, 0x0000000000000001).”, after clicking on the Continue button it breaks again and shows “Unhandled exception at 0x00007FF822ACBD3E (KernelBase.dll) in Pixeval.exe: 0xC0000602: A fail fast exception occurred. Exception handlers will not be invoked and the process will be terminated immediately.”. You can find the screenshots in the section below.

Note: I also subscribed to the TaskScheduler.UnobservedTaskException and AppDomain.CurrentDomain.UnhandledException to make sure every exception is caught even if they’re not supposed to work under this context in principle

Steps to reproduce the bug I failed to reproduce the bug, I tried to create a minimal reproducible example by creating a MainWindow that is exactly the same as the one that I’ve shown above and a page that throws an exception in its Loaded event, but this one runs without any problems, the Application.UnhandledException catches the exception as expected

Expected behavior The exception is caught by the registered global exception handler

Screenshots First time: image Second time: image

Version Info

NuGet package version: [WinUI 3 - Windows App SDK 0.8.1]

Windows app type:

UWP Win32
Yes
Windows version Saw the problem?
Insider Build (xxxxx)
October 2020 Update (19042) Yes
May 2020 Update (19041)
November 2019 Update (18363)
May 2019 Update (18362)
October 2018 Update (17763)
April 2018 Update (17134)
Fall Creators Update (16299)
Creators Update (15063)
Device form factor Saw the problem?
Desktop Yes
Xbox
Surface Hub
IoT

Additional context The stack trace:

 	KernelBase.dll!00007ff822acbd3e()	Unknown
 	combase.dll!RoFailFastWithErrorContextInternal2(HRESULT hrError, unsigned long cStowedExceptions, _STOWED_EXCEPTION_INFORMATION_V2 * * aStowedExceptionPointers) Line 1455	C++
 	CoreMessagingXP.dll!Microsoft::UI::Dispatching::DispatcherQueue::DeferInvokeCallback(void *)	Unknown
 	CoreMessagingXP.dll!CFlat::SehSafe::Execute<<lambda_a81ff790741c2a62f2197c2561f5fe49>>()	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::ActionCallback::ImportAdapter$(class CFlat::Box$1<struct CFlat::FunctionPointerAndUserData$1<long (*)(void *)> > *)	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::Messaging::MessageSession::Callback_InvokeDeferInvoke(class Microsoft::CoreUI::ActionCallback *,struct System::UIntPtr)	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::Dispatch::DeferredCall::Callback_Dispatch(void)	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::Dispatch::DeferredCallDispatcher::Callback_OnDispatch(void)	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::Dispatch::Dispatcher::Callback_DispatchNextItem(void)	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::Dispatch::EventLoop::Callback_RunCoreLoop(enum Microsoft::CoreUI::Dispatch::RunMode)	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::Dispatch::SystemCoreMessaging::Callback_OnGroupDispatch(enum Microsoft::CoreUI::Dispatch::SystemCoreMessaging$GroupPriority,struct CFlat::Ref<struct System::IntPtr>)	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::Dispatch::SystemCoreMessaging::NoContext_GroupDispatchHandler(enum Microsoft::CoreUI::Dispatch::SystemCoreMessaging$GroupPriority,void *)	Unknown
 	CoreMessagingXP.dll!Microsoft::CoreUI::Dispatch::SystemCoreMessaging::NoContext_NormalPriorityDispatchHandler(void *)	Unknown
 	CoreMessaging.dll!00007ff81fde5e1f()	Unknown
 	CoreMessaging.dll!00007ff81fe17a77()	Unknown
 	CoreMessaging.dll!00007ff81fde996b()	Unknown
 	CoreMessaging.dll!00007ff81fde8e26()	Unknown
 	CoreMessaging.dll!00007ff81fde7061()	Unknown
 	CoreMessaging.dll!00007ff81fde6e83()	Unknown
 	user32.dll!00007ff823c0e858()	Unknown
 	user32.dll!00007ff823c0e3dc()	Unknown
 	user32.dll!00007ff823c20bc3()	Unknown
 	ntdll.dll!KiUserCallbackDispatcherContinue()	Unknown
 	win32u.dll!NtUserGetMessage()	Unknown
 	user32.dll!00007ff823c21b3e()	Unknown
 	Microsoft.ui.xaml.dll!00007fff80b69fe7()	Unknown
 	Microsoft.ui.xaml.dll!00007fff80b69f0a()	Unknown
 	Microsoft.ui.xaml.dll!00007fff80b69d23()	Unknown
 	[Managed to Native Transition]	
 	Microsoft.WinUI.dll!ABI.Microsoft.UI.Xaml.IApplicationStatics.Microsoft.UI.Xaml.IApplicationStatics.Start(Microsoft.UI.Xaml.ApplicationInitializationCallback callback)	Unknown
 	Microsoft.WinUI.dll!Microsoft.UI.Xaml.Application.Start(Microsoft.UI.Xaml.ApplicationInitializationCallback callback)	Unknown
>	Pixeval.dll!Pixeval.Program.Main(string[] args) Line 26	C#
 	[Native to Managed Transition]	
 	[Inline Frame] hostpolicy.dll!coreclr_t::execute_assembly(int) Line 89	C++
 	hostpolicy.dll!run_app_for_context(const hostpolicy_context_t & context, int argc, const wchar_t * * argv) Line 246	C++
 	hostpolicy.dll!run_app(const int argc, const wchar_t * * argv) Line 275	C++
 	hostpolicy.dll!corehost_main(const int argc, const wchar_t * * argv) Line 408	C++
 	hostfxr.dll!execute_app(const std::wstring & impl_dll_dir, corehost_init_t * init, const int argc, const wchar_t * * argv) Line 146	C++
 	hostfxr.dll!`anonymous namespace'::read_config_and_execute(const std::wstring & host_command, const host_startup_info_t & host_info, const std::wstring & app_candidate, const std::unordered_map<enum known_options,std::vector<std::wstring,std::allocator<std::wstring>>,known_options_hash,std::equal_to<enum known_options>,std::allocator<std::pair<enum known_options const ,std::vector<std::wstring,std::allocator<std::wstring>>>>> & opts, int new_argc, const wchar_t * * new_argv, host_mode_t mode, wchar_t * out_buffer, int buffer_size, int * required_buffer_size) Line 520	C++
 	hostfxr.dll!fx_muxer_t::handle_exec_host_command(const std::wstring & host_command, const host_startup_info_t & host_info, const std::wstring & app_candidate, const std::unordered_map<enum known_options,std::vector<std::wstring,std::allocator<std::wstring>>,known_options_hash,std::equal_to<enum known_options>,std::allocator<std::pair<enum known_options const ,std::vector<std::wstring,std::allocator<std::wstring>>>>> & opts, int argc, const wchar_t * * argv, int argoff, host_mode_t mode, wchar_t * result_buffer, int buffer_size, int * required_buffer_size) Line 1001	C++
 	hostfxr.dll!fx_muxer_t::execute(const std::wstring host_command, const int argc, const wchar_t * * argv, const host_startup_info_t & host_info, wchar_t * result_buffer, int buffer_size, int * required_buffer_size) Line 566	C++
 	hostfxr.dll!hostfxr_main_startupinfo(const int argc, const wchar_t * * argv, const wchar_t * host_path, const wchar_t * dotnet_root, const wchar_t * app_path) Line 61	C++
 	Pixeval.exe!exe_start(const int argc, const wchar_t * * argv) Line 236	C++
 	Pixeval.exe!wmain(const int argc, const wchar_t * * argv) Line 302	C++
 	[Inline Frame] Pixeval.exe!invoke_main() Line 90	C++
 	Pixeval.exe!__scrt_common_main_seh() Line 288	C++
 	kernel32.dll!00007ff824717034()	Unknown
 	ntdll.dll!RtlUserThreadStart()	Unknown

and the App.xaml.cs

        public App()
        {
            InitializeComponent();
            RegisterUnhandledExceptionHandler();
            AppSetting = AppContext.LoadConfiguration() ?? AppSetting.CreateDefault();
            RequestedTheme = AppSetting.Theme switch
            {
                ApplicationTheme.Dark  => Microsoft.UI.Xaml.ApplicationTheme.Dark,
                ApplicationTheme.Light => Microsoft.UI.Xaml.ApplicationTheme.Light,
                _                      => RequestedTheme
            };
        }

        private void RegisterUnhandledExceptionHandler()
        {
            UnhandledException += (_, args) =>
            {
                Debugger.Break();
            };

            TaskScheduler.UnobservedTaskException += (_, args) =>
            {
                Debugger.Break();
            };

            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                Debugger.Break();
            };

            static async void UncaughtExceptionHandler(Exception e)
            {
                await MessageDialogBuilder
                    .CreateAcknowledgement(Window, MiscResources.ExceptionEncountered, e.ToString()).ShowAsync();
                await ExitWithPushedNotification();
            }
        }

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
dylech30thcommented, Sep 14, 2021

Thanks for the reply. Sorry I can’t reproduce it now, the bug disappears for no reason just like when it came. I will attach the context here as soon as I meet the same problem again.

1reaction
dylech30thcommented, Jul 29, 2021

Similar to https://github.com/microsoft/microsoft-ui-xaml/issues/5221?

Yes I also saw that one, but things goes slightly different since my case is that the exception is thrown from the UI thread where #5221 is actually thrown from a background thread which (in principle) is not supposed to be caught by Application.UnhandledException

Read more comments on GitHub >

github_iconTop Results From Across the Web

Application.UnhandledException Event - Windows
Occurs when an exception can be handled by app code, as forwarded from a native-level Windows Runtime error. Apps can mark the occurrence...
Read more >
App.UnhandledException doesn't catch exceptions from ...
The Application.UnhandledException does not occur when the exception is thrown inside a Page in WinUI 3 Windows App SDK 0.8.1 #5568.
Read more >
Unhandled exception handler not called for Metro / WinRT ...
For example, if a different Windows component calls into application code and an exception is thrown and not caught, the UnhandledException ...
Read more >
DevExpress Project Reunion & WinUI 3 Components
We just released an update to the DevExpress WinUI 3 component suite for Project Reunion (now known as Windows App SDK).
Read more >
Microsoft Windows App SDK 1.0 Stable released, available ...
Microsoft now support deploying WinUI 3 apps without ... the command to publish the project doesn't appear in the menu until you close...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found