Logging an Exception
In addition to handling exceptions, you can also configure the exception handling block to log the exceptions. As mentioned previously, the Exception Handling Block accomplishes this with the help of the Logging Block. To demonstrate logging, add another button named btnLogException
and modify its Click
event as follows:
private void btnLogException_Click
(object sender, EventArgs e)
throw new Exception
("This is a test exception");
catch (Exception ex)
bool rethrow = ExceptionPolicy.HandleException
(ex, "Log Only Policy");
block above invokes the ExceptionPolicy.HandleException
method by passing the exception object (ex
) as well as the policy (the "Log Only Policy" in this case) as arguments. Similar to the exception policies, you also specify logging configuration information in the app.config
file. For example, the app.config
code shown below configures the "Log Only Policy" as a child element of the <exceptionPolicies>
<add name="Log Only Policy">
<add logCategory="Default Category"
|Figure 3. Event Log Entry: The figure shows a sample application log message as seen through the Windows Event Viewer.|
file that you'll find in the downloadable sample code
for this article contains an additional example. For example purposes, the Logging Block simply logs the exceptions in the Windows Application Log, as shown in Figure 3
Note that the logging configuration information in the app.config
file controls the formatting of the log entry.
As you have seen from this article, the exception handling block obviates the need to write the exception handling plumbing code by providing a set of highly reusable classes for handling, logging and processing exceptions. By using these classes, you can reduce errors, bugs, and typos in your application and focus on the core business logic of the application thereby increasing productivity.