C#
  Home arrow C# arrow Page 2 - Exceptions in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
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#

Exceptions in C#
By: Ayad Boudiab
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2008-06-17

    Table of Contents:
  • Exceptions in C#
  • Visual Explained
  • InnerException
  • The Finally Block

  • 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


    Exceptions in C# - Visual Explained


    (Page 2 of 4 )


    The array, a , contains 3 elements at positions 0, 1, and 2. Since there is no fourth element, the program will trigger an error when it tries to execute the line a[3] = 40;

    In exception terminology, we say that an exception was thrown at the line a[3] = 40;

    Because our program did not contain any error handling code, the exception (in this case IndexOutOfRangeException) is bubbled up all the way to the runtime, which handles the exception, prints it on the screen, and terminates the program.

    We can improve this program by handling the exception ourselves. To do this, we surround the code that could cause an exception with a try block, and catch the exception after the try block as such:


    class   Program

    {

    static   void Main( string [] args)

    {

    int [] a = new   int [3];

    try

    {

    a[0] = 10; //ok

    a[1] = 20; //ok

    a[2] = 30; //ok

    a[3] = 40; //No such element.

    }

    catch ( Exception e)

    {

    Console .WriteLine( "Error: accessing an element " +

    "outside the bounds of the array!" );

    }

    }

    }


    So, after we surrounded the code with the try block, we added a catch that catches objects of type Exception. Since the Exception class is the parent of all exceptions, the catch block will catch any exception that might happen in the try block (not necessarily array-related exceptions). The code execution stops at the offending statement (a[3] = 40;), and falls down to the catch blocks (in this case, there is only one).

    If the catch object matched the one being thrown, then the catch block is executed and all other catch blocks are skipped (nothing to skip in this case, because there is only one catch block). The execution is then transferred to any code after the catch blocks. Please note that the exception being thrown is ArrayIndexOutOfBoundException and yet it is caught by an Exception type. This happens because ArrayIndexOutOfBoundException is of type Exception (is-a relationship).

    As mentioned earlier, an Exception object (or any of its descendants) holds very helpful details about the cause of the error. Let's modify the previous code to print out more details about the exception:


    class Program

    {

    static   void Main( string [] args)

    {

    int [] a = new   int [3];

    try

    {

    a[0] = 10; //ok

    a[1] = 20; //ok

    a[2] = 30; //ok

    a[3] = 40; //No such element at position 3.

    }

    catch ( Exception e)

    {

    //printing the exception details

    WriteExceptionDetails(e);

    }

    }


    static   void WriteExceptionDetails( Exception e)

    {

    Console .WriteLine( "Message: {0}" , e.Message);

    Console .WriteLine( "Source: {0}" , e.Source);

    Console .WriteLine( "StackTrace: {0}" , e.StackTrace);

    }

    }


    We factored out the code that prints exception information into a separate method called WriteExceptionDetails(). This method takes an Exception object as a parameter and prints out its details. This is helpful, since we can call this method anywhere in the code for any Exception object. In this case, we simply wrote the details to the output screen. Instead, we could have logged the details into a file that we can analyze later to better improve our code. The Exception object contains properties, such as Message (a nicely formatted message about the cause of the error), Source (the name of the program where the exception happened), and StackTrace (the sequence of calls that triggered the exception).

    More C# Articles
    More By Ayad Boudiab


       · Hello Everyone,Here is my latest article on how to handle exceptions in C#....
     

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT