C#
  Home arrow C# arrow Exception Handling in C#
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Exception Handling in C#
By: Rajesh V S
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 14
    2003-04-23

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    As we all know, exception handling becomes a very handy tool for debugging an application. Rajesh will now explein how one should use Exceptions in C#.

    Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. 

    C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.

    The general form try-catch-finally in C# is shown below 

    try
    {
    // Statement which can cause an exception.
    }
    catch(Type x)
    {
    // Statements for handling the exception
    }
    finally
    {
    //Any cleanup code
    }

    If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.  

    But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. 

    If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto. 

    In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc. 

    Uncaught Exceptions
     
    The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can’t find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program. 

    //C#: Exception Handling
    //Author:
    rajeshvs@msn.com
        
    using System;
    class MyClient
    {
                public static void Main()
                {
                            int x = 0;
                            int div = 100/x;
                            Console.WriteLine(div);
                }
    }

    The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero. 

    //C#: Exception Handling
    //Author:
    rajeshvs@msn.com
    using System;
    class MyClient
    {
                public static void Main()
                {
                            int x = 0;
                            int div = 0;
                            try
                            {
                                        div = 100/x;
                                        Console.WriteLine(“This line in not executed”);
                            }
                            catch(DivideByZeroException de)
                            {
                                        Console.WriteLine("Exception occured");
                                       
                           }
                            Console.WriteLine("Result is {0}",div);
                }
    }

    In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements.

    If a finally block is present, the code inside the finally block will get also be executed.  

    //C#: Exception Handling
    //Author:
    rajeshvs@msn.com
      using System;
    class MyClient
    {
                public static void Main()
                {
                            int x = 0;
                            int div = 0;
                            try
                            {
                                        div = 100/x;
                                        Console.WriteLine("Not executed line");
                            }
                            catch(DivideByZeroException de)
                            {
                                        Console.WriteLine("Exception occured");
                            }
                            finally
                            {
                                        Console.WriteLine("Finally Block");
                            }
                            Console.WriteLine("Result is {0}",div);
                }
    }

    Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.

    //C#: Exception Handling
    //Author:
    rajeshvs@msn.com
     using System;
    class MyClient
    {
                public static void Main()
                {
                            int x = 0;
                            int div = 0;
                            try
                            {
                                        div = 100/x;
                                        Console.WriteLine("Not executed line");
                            }
                            finally
                            {
                                        Console.WriteLine("Finally Block");
                            }
                            Console.WriteLine("Result is {0}",div);
                }
    }
     

    But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block 

    Multiple Catch Blocks
     
    A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error. 

    //C#: Exception Handling: Multiple catch
    //Author:
    rajeshvs@msn.com
    using System;
    class MyClient
    {
                public static void Main()
                {
                            int x = 0;
                            int div = 0;
                            try
                            {
                                        div = 100/x;
                                        Console.WriteLine("Not executed line");
                            }
                            catch(DivideByZeroException de)
                            {
                                        Console.WriteLine("DivideByZeroException" );
                            }
                            catch(Exception ee)
                            {
                                        Console.WriteLine("Exception" );
                            }
                            finally
                            {
                                        Console.WriteLine("Finally Block");
                            }
                            Console.WriteLine("Result is {0}",div);
                }
    }
     

    Catching all Exceptions
     
    By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.  

    //C#: Exception Handling: Handling all exceptions
    //Author:
    rajeshvs@msn.com
     using System;
    class MyClient
    {
                public static void Main()
                {
                            int x = 0;
                            int div = 0;
                            try
                            {
                                        div = 100/x;
                                        Console.WriteLine("Not executed line");
                            }
                            catch
                            {
                                        Console.WriteLine("oException" );
                            }
                            Console.WriteLine("Result is {0}",div);
                }
    }
     

    The following program handles all exception with Exception object.

    //C#: Exception Handling: Handling all exceptions
    //Author:
    rajeshvs@msn.com
    using System;
    class MyClient
    {
                public static void Main()
                {
                            int x = 0;
                            int div = 0;
                            try
                            {
                                        div = 100/x;
                                        Console.WriteLine("Not executed line");
                            }
                            catch(Exception e)
                            {
                                        Console.WriteLine("oException" );
                            }
                            Console.WriteLine("Result is {0}",div);
                }
    }

    Throwing an Exception
     
    In C#, it is possible to throw an exception programmatically. The ‘throw’ keyword is used for this purpose. The general form of throwing an exception is as follows.

    throw exception_obj; 

    For example the following statement throw an ArgumentException explicitly.

    throw new ArgumentException(“Exception”); 

    //C#: Exception Handling:
     //Author:
    rajeshvs@msn.com
    using System;
    class MyClient
    {
                public static void Main()
                {
                            try
                            {
                                        throw new DivideByZeroException("Invalid Division");
                            }
                            catch(DivideByZeroException e)
                            {
                                        Console.WriteLine("Exception" );
                            }
                            Console.WriteLine("LAST STATEMENT");
                }
    }
     

    Re-throwing an Exception

    The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this.  

    //C#: Exception Handling: Handling all exceptions
    //Author:
    rajeshvs@msn.com
    using System;
    class MyClass
    {
                public void Method()
                {
                            try
                            {
                                        int x = 0;
                                        int sum = 100/x;
                            }
                            catch(DivideByZeroException e)
                            {
                                        throw;
                            }
                }
    }
    class MyClient
    {
                public static void Main()
                {
                            MyClass mc = new MyClass();
                            try
                            {
                                        mc.Method();
                            }
                            catch(Exception e)
                            {
                                        Console.WriteLine("Exception caught here" );
                            }
                            Console.WriteLine("LAST STATEMENT");
                }
    }
     

    Standard Exceptions
     
    There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc. 

    The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.

    System.OutOfMemoryException

    System.NullReferenceException

    System.InvalidCastException

    System.ArrayTypeMismatchException

    System.IndexOutOfRangeException        

    System.ArithmeticException

    System.DevideByZeroException

    System.OverFlowException

    User-defined Exceptions
     
    In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.

    //C#: Exception Handling: User defined exceptions
    //Author:
    rajeshvs@msn.com
    using System;
    class MyException : Exception
    {
                public MyException(string str)
                {
                            Console.WriteLine("User defined exception");
                }
    }
    class MyClient
    {
                public static void Main()
                {
                            try
                            {
                                        throw new MyException("RAJESH");
                            }
                            catch(Exception e)
                            {
                                        Console.WriteLine("Exception caught here" + e.ToString());
                            }
                            Console.WriteLine("LAST STATEMENT");
                }
    }

    Design Guidelines

    Exceptions should be used to communicate exceptional conditions. Don’t use them to communicate events that are expected, such as reaching the end of a file. If there’s a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the class-use that one rather than defining a new exception class, and put specific information in the message.

    Finally, if code catches an exception that it isn’t going to handle, consider whether it should wrap that exception with additional information before re-throwing it.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More C# Articles
    More By Rajesh V S

     

    IBM® developerWorks developerWorks - FREE Tools!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! Develop Systems Software Assets with IBM Rational Asset Manager

    Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager.
    FREE! Go There Now!


    NEW! Evaluate Rational Business Developer V7.1

    Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! IBM Rational ClearCase Innovator's Series

    Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase.
    FREE! Go There Now!


    NEW! Maintaining QoS and Process Integrity in an SOA Environment

    This webcast outlines the best practices that must be instituted to gain the maximum benefit from SOA while maintaining high quality of service. Whether you are deploying new applications or managing and monitoring your existing infrastructure, learn how you can ensure high quality of services with SOA based solutions from IBM. All registrants who attend this live Web Seminar will receive complimentary access to a white paper titled “Maintaining QoS in an SOA Environment”.
    FREE! Go There Now!


    NEW! Rational Build Forge Express eKit

    Rational Build Forge Express Edition is an automation framework that packages the latest enterprise-grade technologies into a reliable, flexible and robust configuration designed and priced specifically for small to midsize businesses. The new Rational Build Forge Express eKit provides you with valuable resources – including a case study, podcast, demo, and articles – to help you increase staff productivity, compress development cycles and deliver better software, fast.
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! Webcast: Extreme transaction processing with WebSphere Extended Deployment

    In this webcast, you'll get an introduction to the eXtreme Transaction Processing (XTP) features of WebSphere Extended Deployment and the common architectural traits required by XTP applications. See how WebSphere Extended Deployment's ObjectGrid feature provides a state-of-the-art infrastructure for hosting XTP applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    C# ARTICLES

    - Introduction to Objects and Classes in C#, P...
    - Visual C#.NET, Part 1: Introduction to Progr...
    - C# - An Introduction
    - Hotmail Exposed: Access Hotmail using C#
    - Razor Sharp C#
    - Introduction to Objects and Classes in C#
    - Making Your Code CLS Compliant
    - Programming with MySQL and .NET Technologies
    - Socket Programming in C# - Part II
    - Socket Programming in C# - Part I
    - Creational Patterns in C#
    - Type Conversions
    - Creating Custom Delegates and Events in C#
    - Inheritance and Polymorphism
    - Understanding Properties in C#







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway