Throwing and Catching Exceptions

In .NET languages such as C# and VB.NET, all exceptions will be of either type System.Exception or types derived from System.Exception. The CLR System namespace includes a number of exception types that can use your program. These exception types include ArgumentNullException and InvalidCastException. You can guess their use based on their name. For example, an ArgumentNullException is thrown when an argument to a method is null when null is not an expected (or acceptable) value.

The Throw Statement

To signal an abnormal condition in a .NET program, throw an exception. To do this, use the keyword throw. The following line of code creates a new instance of System.Exception and throws it:

image with no caption

throw new System.Exception(  );

image with no caption

Throw New System.Exception(  )

If you throw an exception and no try/catch block can handle it, your program will come to a grinding halt and display an ugly message, as shown in Figure 21-2.

Throwing an uncaught exception

Figure 21-2. Throwing an uncaught exception

Note

To reproduce this ugly situation for yourself, create the form as shown, and in the click event handler for the Throw button, add the code:

throw new System.Exception(  );

or download the program NoTryCatch ...

Get Programming .NET Windows Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.