C# throw statement

In this chapter you will learn:

  1. What is C# throw statement
  2. Throwing an exception
  3. Example throw statement
  4. Rethrowing an exception
  5. Throw Exception in finally 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 w w  w .  jav a2s .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 w  w.  j a v  a2 s  .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  v a  2s  . c  o m*/
{
  ... // Parse a DateTime from XML element data
}catch (FormatException ex){
  throw new XmlException ("Invalid DateTime", ex);
}

Example 2


using System;//  w  w  w.  j  a v a 2s .co m
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.

Next chapter...

What you will learn in the next chapter:

  1. What is C# System Exception
  2. Common Exception Types
  3. Use the NullReferenceException
  4. Use ArgumentNullException
  5. Use OverflowException
  6. Use DivideByZeroException
Home »
  C# Tutorial »
    C# Language »
      C# Exception
C# Exception
C# Exception classes
C# try Statements and Exceptions
C# catch Clause
C# finally Block
C# throw statement
C# System Exception