C# throw statement

Description

Exceptions can be thrown either by the runtime or in user code.

Syntax

The general form is:

throw exceptOb;

The exceptOb must be an object of an exception class derived from Exception.

Example

In this example, Display throws a System.ArgumentNullException:


using System;//from www . j a  va 2  s  . c  o m
class Test
{
  static void Display (string name)
  {
    if (name == null)
      throw new ArgumentNullException ("name");

    Console.WriteLine (name);
  }

  static void Main()
  {
    try { Display (null); }
    catch (ArgumentNullException ex)
    {
      Console.WriteLine ("Caught the exception");
    }                                                                                         
  }                                                                                           
} 

The code above generates the following result.

Rethrowing an exception

You can capture and rethrow an exception as follows:


try {  ...  }//from w ww . jav  a 2s  . c o  m
catch (Exception ex)
{
  // Log error
  ...
  throw;          // Rethrow same exception
}

Rethrowing in this manner lets you log an error without swallowing it.

Rethrow a more specific exception type. For example:


try//  ww w  .ja va2s  .  com
{
  ... // Parse a DateTime from XML element data
}catch (FormatException ex){
  throw new XmlException ("Invalid DateTime", ex);
}

Example 2


using System;//  ww  w  .  j  a v  a 2 s.  com
using System.Collections;

public class MainClass
{
    static void Main() {
        try {
            try {
                ArrayList list = new ArrayList();
                list.Add( 1 );

                Console.WriteLine( "Item 10 = {0}", list[10] );
            }
            finally {
                Console.WriteLine( "Cleaning up..." );
                throw new Exception( "I like to throw" );
            }
        }
        catch( ArgumentOutOfRangeException ) {
            Console.WriteLine( "Oops!  Argument out of range!" );
        }
        catch {
            Console.WriteLine( "Done" );
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception