April 6, 2020
Hot Topics:

Perform Exception Handling in .NET Exceptionally

  • By Mark Strawmyer
  • Send Email »
  • More Articles »

An exception is an error condition or unexpected behavior that occurs within an application. Exceptions can occur from within classes in the Microsoft .NET Framework or other classes you use. You also can raise them in your own code. Exceptions can result from various conditions, such as the following:

  • Attempting to access a null object's property or method
  • Indexing into an array location that is out of bounds
  • Trying to access an unavailable system resource
  • Executing an invalid SQL statement against a database

When such conditions occur, the offending code throws (or raises) an exception. The exception is passed back up the calling stack until it is handled (or caught), or the application terminates due to the unhandled exception.

Exception handling is a structured form of error handling that differs from the unstructured error handling many traditional Visual Basic developers are accustomed to using. In unstructured error handling such as the On Error Goto of old, the block of code has the same error handler regardless of the error that occurs. In structured error handling, any number of different error filtering conditions can be set in place for a block of code. Structured error handling allows you to dictate proper programming to those who use your code. In the past, an error could occur from a call to your code and you would have no way to ensure that the calling code had to account for an unknown condition. Through exceptions, your method can return an exception and force the caller to account for the possible exceptions in some way.

Existing Exceptions

The .NET Framework contains a number of exceptions that all derive from the base class System.Exception. It is easier to rely on existing exceptions where possible, and create new types only when necessary. The following list contains some of the more common exceptions:

  • ArgumentException—invalid argument of some sort passed to a method
  • ArgumentNullException—used by methods that don't allow arguments to be null
  • DivideByZeroException—attempt to divide by zero
  • IndexOutOfRangeException—improper index into an array
  • InvalidCastException—results from an invalid cast or explicit conversion attempt
  • InvalidOperationException—object is in an invalid state with respect to method call
  • NullReferenceException—when a null object is referenced

Using Exceptions

Structured exception handling has three main parts. The code that you are attempting to execute is contained within a try block. The exception(s) are captured for handling through the use of trailing catch blocks. Different types of exceptions are handled through consecutive catch statements. Each catch statement handles a different exception. The ordering of the catch statements should flow from most specific to most general. An optional finally block can follow a sequence of catch blocks. No matter what happens with the code contained within the try block, the code contained within the finally block always executes. This allows you the option to clean up after the try block (for example, when a database connection was opened and needs to always be closed after use).

Exception Handling Sample Code

The following code represents a traditional try...catch...finally sequence:

try{   // Some code here, such as array access, method call, or   // accessing a database}catch( IndexOutOfRangeException outRangeEx ){   // Specific exception handler}catch( InvalidOperationException invalidOpEx ){   // Specific exception handler}...finally{   // Clean up from try, such as closing database connection}

The following sample code represents a try...finally statement:

try{   // Some code here, such as array access, method call, or   // accessing a database}finally{   // Clean up from try, such as closing database connection}

This statement ensures that the finally block, which is typically used to clean up whatever occurred in the try block, executes, but it allows the exception to be propagated back up the call stack. In addition—although not necessarily recommended—you can have a try...catch without specifying a specific exception to catch:

try{   // Some code here, such as array access, method call, or   // accessing a database}catch{   // Generic exception handler}

Page 1 of 2

This article was originally published on November 10, 2004

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date