Mobile Zone is brought to you in partnership with:

Matt has been paid to develop software for the past 12 years. He specializes in mobile and web development and has recently been doing a lot with Windows Phone 7. He runs DevEvening (http://devevening.co.uk/) a .net focused user group in Surrey and the Windows Phone User Group (http://wpug.net/) in London. He blogs at http://blog.mrlacey.co.uk/ and tweets at @mrlacey & @wpug. Matt is a DZone MVB and is not an employee of DZone and has posted 102 posts at DZone. You can read more from them at their website. View Full User Profile

Catching an uncatchable exception

08.20.2011
| 4305 views |
  • submit to reddit
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.
References
Published at DZone with permission of Matt Lacey, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)