Throw Statement in C#

All along we have been talking about catching exceptions, but you may have been wondering who is throwing them or how you can throw one yourself. If an exception occurs during the evaluation of an expression, the language runtime automatically throws the appropriate exception. If an exception must be thrown programmatically, you would use the throw statement. Listing 7.9 gives an example of using the throw statement.

Listing 7.9: Exception9.cs, Throw Example

using System;

public class ThrowTest
{
    public static void fn(Int32 age)
    {
        if (age < 0)
        {
            // throw an argument out of range exception if the age is
            // less than zero.
            throw new ArgumentOutOfRangeException("Age Cannot Be Negative ");
        }
    }

    public static void Main()
    {
        try
        {
            fn(-10);
        }

        catch (Exception e)
        {
            Console.WriteLine(String.Concat(e.StackTrace, e.Message));
            Console.ReadLine();
        }
    }
}

Figure 7.5 below shows the result of throwing the argument out of range exception and displaying it in the catch block:

Throw Statement in C#

Figure 7.5: Output of Listing 7.9

In this example we have a function called fn, which takes age as an argument. In this function we check if the age is a negative value, and if so, throw ArgumentOutOfRangeException. As you can see, throwing an exception is a fairly simple task.

Let's modify this example, as shown in Listing 7.10.

Listing 7.10: Exception10.cs

using System;
using System.Text;

public class ThrowTest
{
    public static void fn(Int32 age)
    {
        if (age < 0)
        {
            throw new ArgumentOutOfRangeException(
            "Age Can Not Be Negative ");
        }
    }

    public static void Main()
    {
        try
        {
            try
            {
                fn(-10);
            }

            catch (Exception e)
            {
                Console.WriteLine(String.Concat(e.StackTrace, e.Message));
                throw;
            }

            // or we could also have called throw e ;
        }
 
        catch (Exception e)
        {
            Console.WriteLine("In the outer catch");
            Console.WriteLine(String.Concat(e.StackTrace, e.Message));
            // Executing this statement would cause a
            // NullreferenceException
            //Console.WriteLine(e.InnerException.Message);
        }
        Console.ReadLine();
    }
}

In Listing 7.10 we add a throw statement in the catch block basically rethrowing System.Exception causing the same exception to occur in the catch clause. So, if we have one more try block outside the inner try block, the outer try-catch block catches the exception.

The output for the program in Listing 7.10 is shown in Figure 7.6.

Throw Statement in C#

Figure 7.6: Output of Listing 7.10

One last thing about the throw statement: you will never need to throw system exceptions such as IndexOutOfRange or NullReferenceException, which are thrown normally by the runtime. The .NET framework developer specification requires that you don't throw these exceptions programmatically. However, if you really wanted to do it, you could write a piece of code that throws these exceptions programmatically and compiles and executes successfully.

Conclusion

Hope this article would have helped you in understanding Throw Statement in C#. See other articles on the website on .NET and C#.


Recommended Free Ebook
Similar Articles