Export (0) Print
Expand All

Throwing Exceptions from Components

Visual Studio .NET 2003

Any exception that occurs in your component but is not handled will automatically be thrown to the client application. For example, the following will throw an OverflowException.

C# Note In order to throw the overflow exception, you must set Check for overflow underflow to true in the Build property page in the Configuration Properties folder of the Project Properties dialog box.
' Visual Basic
Dim XX As Integer = 100000
Dim YY As Integer = 100000
Dim ZZ As Integer
' The resulting value is to large to be contained by an integer, thus 
' the overflow error is thrown.
ZZ = XX * YY

// C#
int number1 = 100000;
int number2 = 100000;
int product;

// The resulting value is to large to be contained by an integer, 
// thus the overflow error is thrown.
product = number1 * number2;

If this exception is not handled in the component that generates it, the exception will be bubbled up the call stack until it either finds an appropriate error handler, or the common language runtime default error handler handles it. If you want to pass standard runtime exceptions to the client application, no additional coding is necessary. It will happen automatically.

In areas of code where you suspect an exception might be thrown, you will probably want to provide additional information to the developers using your component.

The following example shows how to catch the exception as it is thrown, and pass it to the client application along with additional information in the message property:

' Visual Basic
' The code in the Try block is the code expected to cause an error.
Dim XX As New Integer = 100000
Dim YY As New Integer = 100000
Dim ZZ As Integer
Try
   ' The resulting value is to large to be contained by an integer, thus 
   ' the overflow error is thrown.
   ZZ = XX * YY
' If an overflow exception is generated, it will be caught here.
Catch e as OverflowException
   ' Throws a new exception that provides information in the message 
   ' string and provides the original exception as the InnerException, e.
   Throw New OverflowException( _
   "The value for the product was larger than an integer could hold", e)
' Catches any other kind of exception that might be generated.
Catch e as Exception
   Throw e
End Try

// C#
// The code in the try block is the code expected to cause an error.
int number1 = 100000;
int number2 = 100000;
int product;
try
{
   product = number1 * number2;
}
// If an overflow exception is generated, it will be caught here.
catch (OverflowException e)
{
   // Thows a new exception that provides information in the message
   // string and sends on the original exception e.
   throw new OverflowException(
      "The value for the product is larger than an integer can hold.", e);
}
// Catches any other kind of exception that might be generated.
catch (Exception e)
{
   throw e;
}

In the preceding example, an exception is thrown when the overflow condition is generated. This exception is caught by the Catch block, which then throws a new exception that contains an informative message and the original exception in the InnerException property. This new exception is then bubbled up the call stack until it is handled.

To provide additional information when throwing exceptions

  1. Determine which parts of your code are likely to throw exceptions, and what exceptions might be thrown.
  2. Enclose these areas of code within a Try...End Try block.
  3. Use the Catch statement to catch specific exceptions. For example:
    ' Visual Basic
    Catch e as OverflowException
       ' Handling code omitted.
    Catch e as NullReferenceException
       ' Handling code omitted.
    
    // C#
    catch (OverflowException e)
    {
       // Handling code omitted.
    }
    catch (NullReferenceException e)
    {
       // Handling code omitted.
    }
    
  4. Within the Catch block, Throw a new exception that provides information in the message property and wraps the original exception in the InnerException property. An example is shown:
    ' Visual Basic
    Catch e as OverflowException
       Throw New OverflowException( _
          "An overflow occurred in the Widget component.", e)
    
    // C#
    catch (OverflowException e)
    {
       throw new OverflowException(
          "An overflow occurred in the Widget component.", e);
    }
    

Custom Exceptions

If you want to throw a custom exception to the client application, you have that opportunity. You must first create a new exception that inherits from the Exception class or a derived class. You must then determine the conditions under which this exception will be thrown, and write the appropriate code to throw the exception.

To create and throw a custom exception

  1. Create a custom exception class. This class should inherit System.Exception or a class derived from System.Exception. An example is shown below.
    ' Visual Basic
    Public Class SpeedOfLightException
       Inherits System.Exception
       ' Creates a constructor for the exception that allows you to set the 
       ' message property when thrown.
       Public Sub New(ByVal Message As String)
          MyBase.New(Message)
       End Sub
    End Class
    
    // C#
    public class SpeedOfLightException:System.Exception
    {
       //Creates a constructor for the exception that allows you to set the
       // message property when thrown.
       public void SpeedOfLightException(string Message):base(Message)
       {
       }
    }
    
  2. Decide how you intend to use your exception, and when you want to throw it. You should examine your code and determine those parts where error situations are possible, but a standard exception will not be thrown.
  3. When you have determined how your custom exception is to be used, test for error conditions and throw your exception when appropriate. For example:
    ' Visual Basic
    Public Sub Accelerate(ByVal finalVelocity as Integer)
       If finalVelocity > cnstSpeedOfLight then
          Throw New SpeedOfLightException("You cannot exceed light speed!")
       End If
       ' (Additional code omitted)
    End Sub
    
    // C#
    public void Accelerate(int finalVelocity)
    {
       if (finalVelocity > cnstSpeedOfLight)
       {
         throw new 
            SpeedOfLightException("You cannot exceed light speed!");
       }
       // Additional code omitted.
    }
    

    The preceding code receives a value as an argument. It then checks to see if this argument is greater than a constant, and if so throws a SpeedOfLightException. This exception is bubbled up to the calling method, which will then decide how to deal with it.

  4. If your component will be exposed to COM, you must determine and set an appropriate Hresult value for your exception. For details, see Exception.HResult Property.

See Also

Best Practices for Throwing Exceptions from Components

Show:
© 2014 Microsoft