SIGN UP MEMBER LOGIN:    
ARTICLE

Throw Statement in C#

Posted by Puran Mehra Articles | C# Language December 20, 2009
In this article I will explain you about Throw Statement in C#.
Reader Level:
Download Files:
 

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

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:

fig7.9.gif

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.

fig7.10.gif

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#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor