Exercise 1: Log exception information
With this exercise, you will add local and global exception handling in an application with no exception handling, and log in to the Windows event log.
First step
Open the Puzzler.sln project, the default installation path should be C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\exception EXERCISES\EX01, and compiled.
Second Step review application
Select Debug | The Start Debugging menu command runs the application, and the current application does not receive exception information. When you try to add a word with a number (enter "abc123" in the text box and click the Add Word button) to the table of contents, an unhandled exception occurs, and debugging is interrupted.
Select Debug | The Stop Debugging menu command exits the application and returns to visual Studio.
Third step to increase Try/catch exception handling
1. Select the Puzzlerui project and select Project | Add Reference ... menu command, select the Browse item and add the following assembly.
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll
The default installation location is C:\Program Files\Microsoft Enterprise Library January 2006\bin.
2. Select the Puzzler.cs file in Solution Manager and select View | Code menu command, add the following namespaces.
Using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
3. Add the following code in the Btnaddword_click method to add the Try/catch area when calling Addword and SetError.
private void btnAddWord_Click(object sender, System.EventArgs e)
{
try
{
// TODO: Handle exceptions
PuzzlerService.Dictionary.AddWord(txtWordToCheck.Text);
errorProvider1.SetError(txtWordToCheck, "");
}
catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "UI Policy");
if (rethrow)
throw;
MessageBox.Show(string.Format(
"Failed to add word {0}, please contact support.",
txtWordToCheck.Text));
}
}
Note that it is important to use the throw statement here, not to use throw ex. If you use throw ex, the exception information is repackaged again at the point where the exception is thrown, which does not achieve the desired effect.