Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Ads by Lake Quincy Media
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » Exception Statements in C#

Exception Statements in C#

In this article I will explain you about Exception Statements in C#.

Author Rank:
Total page views :  2036
Total downloads :  10
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
TryCatch.zip
 
Become a Sponsor


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

C# supports structured exception handling similar to that seen in C++. In structured exception handling, you write code surrounded by blocks. If an exception occurs, the block throws the execution control to a predefined handled code. The try, catch, finally statements define these blocks. In other words, if an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a try statement. Application code within a try statement is a try block. Application code that handles exceptions thrown by a try block is placed within a catch statement and is called a catch block. In a try block, you define the code you want to execute and protect from any possible errors. The catch block defines the handlers for the exception. The finally block is used to free resources allocated in the try block.

The try statement provides a mechanism to capture exceptions in a block of code and a mechanism to execute blocks of code both under normal circumstances and when an exception occurs.

You can define a try statement in a few different forms:

  • try-catch
  • try-finally
  • try-catch-finally

Let's discuss each one of them below.

Try-Catch

In try-catch, a try block is followed by one or more catch blocks. You basically surround the block of code where you expect an error to occur with the try statement followed by one or more catch blocks to handle one or more types of exceptions. Let's look at the example in Listing 7.1 to understand it better:

Listing 7.1: Exception1.cs, Try-Catch Example

using
System;
using
System.Text;

public
class LearnAboutTryCatch1
{
    public static void GenerateException(Int32 arg1, Int32 arg2)
    {
        Int32 result1;
        result1 = 0;

        try
        {
            //BLOCK OF CODE WHERE ERRORS ARE EXPECTED
            //division
            result1 = arg1 / arg2;
            Console.WriteLine(result1);
        }

        catch (System.DivideByZeroException e)
        {
            //HANDLE THE ERROR
            //StackTrace gives us the location of error as string
            Console.WriteLine(String.Concat(e.Message, e.StackTrace));
            //e.Message: gives the error message in this case,
            //Attempted to divide by zero.
            //e.Stacktrace: gives the location of the error in text
            //form. In this case at
            //LearnAboutTryCatch1.GenerateDivideByZeroError(Int32
            // Numerator,Int32 Denominator)
            //in this case the output would be
            //Attempted to divide by zero. at
            //LearnAboutTryCatch1.GenerateDivideByZeroError(
            // Int32 Numerator,Int32 Denominator)
        }
    }

    public static void Main()
    {
        GenerateException(6, 0);
        Console.ReadLine();
    }
}


Output of above listing:

fig7.1.gif

First we create the class LearnAboutTryCatch1, which has the method GenerateException that divides two numbers. The block of code where we would expect errors in this case, the division operation is surrounded by the try clause. The try clause is followed by a catch statement, which has an argument of type System.DivideByZeroException to catch divide-by-zero errors. If you divide a number by zero, this causes a divide-by-zero exception.

You have to handle all of the exceptions inside the catch clause. In this example, the block of code inside the catch clause writes a message to console. Note that we have concatenated the Message property and the StackTrace property of the exception to generate the message. The Message property gives the actual error message, and the StackTrace gives the location of the actual error. Finally in the Main() method, we call the function by passing 6 and 0 to generate a divide-by-zero error. Now, in Listing 7.2, we will modify the code above to illustrate how to use multiple catch statements:

Listing 7.2: Exception2.cs, Second Exception Example


using
System;
using
System.Text;

public
class LearnAboutTryCatch2
{
    public static void GenerateException(Int32 arg1, Int32 arg2)
    {
        Int32 result1 = 0;
        Int32 result2 = 0;

        try
        {
            //BLOCK OF CODE WHERE ERRORS ARE EXPECTED
            //division
            result1 = arg1 / arg2;
            //multiplication
            result2 = arg1 * arg2;
            Console.WriteLine(result1);
            Console.WriteLine(result2);
        }

        catch (System.DivideByZeroException e)
        {
            //HANDLE THE ERROR
            //StackTrace gives us the location of error as
            // string
            Console.WriteLine(String.Concat(e.Message, e.StackTrace));

            //e.Message: gives the error message, in this
            // case, Attempted to divide by zero.
            //e.Stacktrace: gives the location of the error
            //in text form. In this case at
            // LearnAboutTryCatch1.GenerateDivideByZeroError(Int32 Numerator,Int32 Denominator)
            //in this case the output would be
            //Attempted to divide by zero. at
            //LearnAboutTryCatch1.GenerateDivideByZeroError(
            // Int32 Numerator,Int32 Denominator)
        }

        catch (System.OverflowException e)
        {
            //HANDLE THE ERROR
            //StackTrace gives us the location of error as
            // string
            Console.WriteLine(String.Concat(e.Message, e.StackTrace));

            //e.Message: gives the error message in this case,
            //e.Stacktrace: gives the location of the
            // error in text form.
        }
    }

    public static void Main()
    {
        GenerateException(6, 0);
        GenerateException(999999999, 999999999);
        Console.ReadLine();
    }
}


Figure 7.2 shows the output of Listing 7.2 in the console. Note that it shows the divide by zero error and its location in the code.

fig7.2.gif

Figure 7.1: The Output of Listing 7.2

We have added a multiplication operation inside the GenerateException function, and we have also added one more catch clause to handle System.OverflowException, which could result from multiplying two big numbers. For example, if the resulting value of the multiplication is bigger than what an Int32 type can hold, we would expect to get an overflow exception so we have to add one catch block for each exception. Hence, this example, Listing 7.2, demonstrates how to handle more than one type of exception.

Assume that we have passed 999999999 as arg1 and 999999999 as arg2 to the GenerateException method. Note that result2 is Int32 type, and when we multiply 999999999 and 999999999, we get a stack overflow error.

Compile the code as usual with the following command:

csc LearnAboutTryCatch2.cs.

Once you run LearnAboutTryCatch2.exe, you would expect that both the divide-by-zero and the overflow exceptions would be thrown. However, you would be surprised to know that only the divide-by-zero exception is raised and not the overflow exception because result1=arg1/arg2; code comes first.

What if you want to change this behavior? This leads us to the next important concept, checked and unchecked statements in C#.

The different ways of controlling overflow behavior are listed below:

  • Set the compiler option to checked+ or checked–
  • Add the checked statement and unchecked statement to your code Compiler options apply to the application level whereas checked and unchecked statements can apply to specific blocks of code. Checked and unchecked statements always override the compiler options, so if you have compiled with the checked+ option and have a block of code surrounded by an unchecked statement, the overflow exception will not be raised for any overflow conditions within the unchecked block. Similarly, if you have compiled with the checked– option and have a block of code surrounded by the checked statement, the overflow exception would be raised for any overflow conditions within the checked block of code. Listing 7.3 shows what the code looks like after adding the checked statement.

Listing 7.3: Exception3.cs, Checked-Unchecked Example

using
System;
using
System.Text;

public
class LearnAboutTryCatch1
{
    public static void GenerateException(Int32 arg1, Int32 arg2)
    {
        Int32 result1 = 0;
        Int32 result2 = 0;

        try
        {
            //BLOCK OF CODE WHERE ERRORS ARE EXPECTED
            //division
            result1 = arg1 / arg2;

            //multiplication
            checked
            {
                result2 = arg1 * arg2;
            }

            Console.WriteLine(result1);
            Console.WriteLine(result2);
        }

        catch (System.DivideByZeroException e)
        {
            //HANDLE THE ERROR
            //StackTrace gives us the location of error
            // as string
            //e.Message: gives the error message in this
            Console.WriteLine(String.Concat(e.Message, e.StackTrace));

            // case, Attempted to divide by zero.
            //e.Stacktrace: gives the location of the error
            // in text form. In this case at
            // LearnAboutTryCatch1.GenerateDivideByZeroError(
            // Int32 Numerator,Int32 Denominator)
            //in this case the output would be
            //Attempted to divide by zero. at
            // LearnAboutTryCatch1.GenerateDivideByZeroError(
            // Int32 Numerator,Int32 Denominator)
        }

        catch (System.OverflowException e)
        {
            //HANDLE THE ERROR
            //StackTrace gives us the location of error as
            //string.
            //e.Message: gives the error message in this
            // case,
            //e.Stacktrace: gives the location of the error
            // in text form.
            Console.WriteLine(String.Concat(e.Message, e.StackTrace));
        }
    }

    public static void Main()
    {
        GenerateException(6, 0);
        GenerateException(999999999, 999999999);
        Console.ReadLine();
    }
}


Figure 7.2 illustrates the output of the overflow exception to the console resulting from using the checked keyword in Listing 7.3.

fig7.3.gif

Figure 7.2: Output of Listing 7.3

The code in Listing 7.3 would raise both exceptions: the divide-by-zero exception and the overflow exception. We leave it to you as an exercise to play with different combinations of compiler options, as well as checked and unchecked statements.

Now, let's say we want to capture all other exceptions other than the specific exceptions described here (DivideByZeroException and OverflowException). To do that we have to add another catch statement with the argument of type System.Exception. By adding the System.Exception, the code now will look like Listing 7.4. Pay specific attention to the place where we insert the catch statement.

Listing 7.4: Exception4.cs, General Exception Example

using
System;
using
System.Text;

public
class LearnAboutTryCatch1
{
    public static void GenerateException(Int32 arg1, Int32 arg2)
    {
        Int32 result1 = 0;
        Int32 result2 = 0;

        try
        {
            //BLOCK OF CODE WHERE ERRORS ARE EXPECTED
            //division
            result1 = arg1 / arg2;
            //multiplication

            checked
            {
                result2 = arg1 * arg2;
            }
            Console.WriteLine(result1);
            Console.WriteLine(result2);
        }

        catch (System.DivideByZeroException e)
        {
            //HANDLE THE ERROR
            //StackTrace gives us the location of error as string
            //e.Message: gives the error message, in this
            // case, Attempted to divide by zero.
            Console.WriteLine(String.Concat(e.Message, e.StackTrace));

            //e.Stacktrace: gives the location of the error in text form. In
            // this case at LearnAboutTryCatch1.GenerateDivideByZeroError(
            // Int32 Numerator,Int32 Denominator)
            //in this case the output would be
            //Attempted to divide by zero. at
            // LearnAboutTryCatch1.GenerateDivideByZeroError(
            // Int32 Numerator,Int32 Denominator)
        }

        catch (System.OverflowException e)
        {
            //HANDLE THE ERROR
            //stackTrace gives us the location of error as string
            //e.Message: gives the error message in this case,
            //e.Stacktrace: gives the location of the error in text
            // form.
            Console.WriteLine(String.Concat(e.Message, e.StackTrace));
        }
    }

    public static void Main()
    {
        GenerateException(6, 0);
        GenerateException(999999999, 999999999);
        Console.ReadLine();
    }
}


Output of above listing:

fig7.4.gif

The compiler would not let you compile the code in Listing 7.4. Instead, it would give you the following error message: "A previous catch clause already catches all exceptions of this or a super type ('System.Exception')." The lesson to learn is you have to first catch specific exceptions and then catch the general exception (System.Exception). We leave it as an exercise for you to change the code above to fix the order of catching exceptions.

As shown in Listing 7.5, there are two ways to catch a general System.Exception. In the first case you would capture the exception and get all the information about it from the Exception parameter. However, in the second code block you would not have access to that information.

Listing 7.5: Try-Catch Syntax


        try
        {    
        }

        catch(Exception e)
        {
        }

        and    

        try
        {
        }

        catch
        {
        }  


Conclusion


Hope this article would have helped you in understanding Exception Statements 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
 About the author
 
Puran Mehra

Working as a Software professional. 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
TryCatch.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.