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.
21.3.1 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:
throw new System.Exception( );
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.
Figure 21-2. Throwing an uncaught exception
|
21.3.2 The Try and Catch Statements
To handle exceptions, take the following steps:
- Execute any code that you suspect might throw an exception (such as code that opens a file or allocates memory) in a try block.
- Catch any exceptions thrown in a catch block.
In C#, a try block is created with the keyword try, and the block is enclosed in braces.
In VB.NET, a try block is created with the keyword Try and ended with the keywords End Try.
In C#, a catch block is created using the keyword catch, and is also enclosed within braces.
In VB.NET, a catch block begins with the keyword Catch and can be terminated by either the next use of the Catch keyword or the End Try statement. Catch statements can be written to catch either specific types of exceptions or all thrown exceptions.
21.3.2.1 The finally statement
In some instances, throwing an exception and unwinding the stack can create a problem. For example, if you have opened a file or otherwise committed a resource, you might need an opportunity to close the file or flush the buffer.
If you want to take action, such as closing a file, regardless of whether an exception is thrown, you have two strategies to choose from. One approach encloses the dangerous action in a try block and then closes the file in both the catch and try blocks. However, this duplication of code is ugly and error prone. C# and VB.NET provide a better alternative in the finally block.
The code in a finally block is guaranteed to be executed regardless of whether an exception is thrown.
|