
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
420
|
Chapter 7: Exception Handling
}
public static object one;
public static string two;
}
When this code is executed, the catch block captures the real exception and there is
no fear of the application shutting down. The text displayed by the
catch block is as
follows:
CAUGHT EXCEPTION IN .CCTOR: System.NullReferenceException: Object reference not set
to an instance of an object.
at Chapter_Code.TestInit..cctor( ) in c:\book cs cookbook\code\test.cs:line 191
This is much cleaner and more elegant than the other solutions. In addition, track-
ing down the source of the bug is much easier. As a note, this exception now oper-
ates in the same manner regardless of whether the application is being run in the
development environment.
See Also
See the “Error Raising and Handling Guidelines” and “TypeInitializationException
Class” topics in the MSDN documentation.
7.17 Handling Exceptions Thrown from an
Asynchronous Delegate
Problem
When using a delegate asynchronously, you want to be notified if the delegate has
thrown any exceptions.
Solution
Wrap the EndInvoke method of the delegate in a try/catch block:
using System;
using System.Threading;
public class AsyncAction
{
public void PollAsyncDelegate( )
{
// Create the async delegate to call Method1 and call its BeginInvoke method.
AsyncInvoke MI = new ...