Subscribe to the RSS feed then follow me on twitter at @mrlacey (misc) and @wpug (WPDev news)

Sunday, August 14, 2011

Catching an uncatchable exception

Recently we had an interesting issue in a Windows Phone 7 app I was working on that proved awkward to address. The code in question related to playing a video via the MediaPlayerLauncher.

The code in question looked like this:
                    new MediaPlayerLauncher { Media = fileUri }
                        .Show();
The issue we had was that if the user triggered the launching of the MediaPlayer and then very quickly hit the back button then they could get the following error.

"Not allowed to call Show() when a navigation is in progress"

As a first we tried wrapping the above code in a simple try..catch block to handle the unhandled exception:
                try
                {
                    new MediaPlayerLauncher { Media = fileUri }
                        .Show();
                }
                catch (Exception exc)
                {
                    ...
                }
But this didn't work.

Next we tried to determine if navigation was in progress by comparing the CurrentSource and Source properties of the page but that didn't work either.

Then I had an idea.
What if we split the separated the generation of the object and the calling of the method?:
                        var mediaLauncher = new MediaPlayerLauncher();
                        mediaLauncher.Media = fileUri;

                        try
                        {
                            mediaLauncher.Show();
                        }
                        catch (InvalidOperationException exc)
                        {
                            ...
                        }
This did allow us to catch and handle the exception. Yay!

I'm a big fan of not writing any code I don't have to and so having to write more than I think should be absolutely necessary here is a little bit disappointing. It's good to know, however that this isn't an exception I can't do anything about.
In this situation I can happily ignore this exception as if the user has hit back shortly after trying to lauch the video it's reasonable to assume they don't actually want to watch it.

Are you a Windows Phone developer? If so, you could be getting rewards for the apps you build and the success they achieve by joining Nokia's DVLUP program.

No comments:

Post a Comment