Exception Handling in Silverlight 4 – Manage Unhandled Exceptions

A good practice to follow is to handle the exception where it occurs, using the try-catch block. However there could be certain areas in your code where unknown exceptions crop up. If the exception is not handled by your application, the exception reaches the Silverlight plug-in and the application ends abruptly.

In order to manage unhandled exceptions gracefully, Silverlight has the Application.UnhandledException event in the App.xaml.cs file which provides centralized error handling. Here’s a sample that shows how to gracefully manage unhandled exceptions.

Open your App.xaml code behind file and look for the Application_UnhandledException method.

image

As seen in the code above, you can log the errors into a log file by accessing the Unhandled Exception via the ‘ExceptionObject’ property. Setting ‘e.Handled’ to true tells the Silverlight application that the exception has been handled and the application can continue running.

Note: For errors that originate from the Silverlight plug-in itself, developers use JavaScript to handle them. If you are using VS 2010, you will see that the template automatically creates an onSilverlightError function that implements basic error handling.

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: