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.


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.


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: