ASP.NET
  Home arrow ASP.NET arrow Page 10 - ASP.NET Basics Part 10: Making Exceptions
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? 
ASP.NET

ASP.NET Basics Part 10: Making Exceptions
By: Harish Kamath (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 12
    2004-01-19

    Table of Contents:
  • ASP.NET Basics Part 10: Making Exceptions
  • Word Games
  • Exceptionally Clever
  • A Custom Job
  • You Throw(), I'll Catch()
  • The More, the Merrier
  • Sending It to the Bitbucket
  • Rolling Your Own
  • Meeting the Family
  • All Wrapped Up
  • Digging Deeper
  • Endgame

  • 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


    ASP.NET Basics Part 10: Making Exceptions - All Wrapped Up


    (Page 10 of 12 )

    Take a close look at this final example on exception handling – it highlights several important concepts that will prove useful when you get down to coding complex business logic in your ASP.NET scripts.


    <%@ Import Namespace="System.Data"%>
    <%@ Import 
    Namespace
    ="System.Data.SqlClient"%>
    <script Language="C#" 
    runat="server">
    void Page_Load
    ()

     

     
    try {
     

      
    // build the connection string
      string strConn = 
    "user id=sa;password=;";
      strConn 
    += "initial catalog=pubs;data 
    source=tatooine;"
    ;
     
      
    // create an instance of the SqlConnection 
    object
      SqlConnection objConn 
    = new 
    SqlConnection(strConn);
      

      
    try {
       
    // create an instance of the Command 
    object
       SqlCommand objCommand 
    = new SqlCommand("SELECT * 

    FROM starwars;"
    objConn);
      

       
    // open the 
    connection
           
     objConn
    .Open();
          

            
    // populate a SqlDataReader 
    object
            SqlDataReader objReader 

    objCommand.ExecuteReader();
      

       
    // set the source of our "starwars" 
    datagrid
            starwars
    .DataSource 
    objReader;
            

            
    // bind the data to the 
    grid
           
     starwars
    .DataBind();
           
     

       
    // close the Reader 
    object
       objReader
    .Close();
           
     

            
    // display output 
    message
            output
    .Text "Star 
    Wars"
    ;
              

      
    } catch (SqlException e) {
     

       
    throw new Exception("The following error occurred: " 
    e.Message);
     
      } catch (
    Exception e) {
     
       throw new 
    Exception("The following error occurred: " 
    e.Message);
     
      } 
    finally {
      

       
    // close the connection 
    object
       objConn
    .Close();
      
    }        
     

           

     
    } catch (SqlException e) {
     

      output
    .Text e.Message;
      

     
    } catch (Exception e) {
     

      output
    .Text e.Message;
      

     
    }  
    }
    </script>

    <html>
    <title>Star 
    Wars</title>
    <body>
    <asp:label id="output" runat="server" 
    />
    <asp:datagrid id="starwars" runat="server"/>
     
    </body>
    </html>

    If all goes well, you should see something like this:

    However, it's quite likely that something might go wrong - for example, the database connection might not open successfully, or there might be an error in the SQL query. Therefore, the cautious ASP.NET developer always wraps his or her code in multiple "try-catch" blocks, to ensure that exceptions are trapped and resolved.

    The example above demonstrates this concept, by nesting multiple "try-catch" blocks within each other. If you were to take out all the business logic from the code listing above, the skeleton would look something like this:


    <%
     
    try {
      
    try {
     
      } catch (
    SqlException e) {
     
      } catch (
    Exception e) {
     
      } 
    finally {
     
     }         
     
     } catch (
    SqlException e) {
     
     } catch (
    Exception e) {
     
    }  

    %>

    In this example, the outermost "try-catch" block is used to handle database connection exceptions, while the inner one is used to resolve exceptions in the query and result set.

    If a connection cannot be opened to the database server, or if an error occurs in the SqlConnection object, an exception will be raised, which can be caught and handled by the outer "try" block. Here's what the output would look like in this scenario:

    But what about the inner "try-catch" block? Well, this handles the SqlCommand and SqlDataReader objects. If, for some reason, you are unable to create these objects - say, the table "starwars" has been deleted by some DBA - you need to inform the user accordingly. This is where the inner block is used, and it generates output like the following:

    A couple of interesting things to note in the example above:

    1. The inner "try-catch" block throws user-defined exception if an error occurs in query or result set processing using the "throw" statement discussed previously. Since the blocks are nested, exceptions generated in an inner block will be propagated upwards to the parent block, and can be managed by the parent block's "catch" handler.

    2. When an exception occurs in the inner block, it implies that an error occurred after the database connection was opened, either during the query phase or the result processing phase. Therefore, when an exception occurs, it becomes necessary to close the database connection before propagating the exception upwards. That's where the inner "finally" block comes in – it contains code that will destroy the SqlConnection object and free up memory associated with the database connection. Since this code is enclosed in a "finally" block, it will be executed without fail.

    In case you're wondering - there's no need to do this in the outer "try-catch" block because there's only one possible exception that could occur within the outer block - a failure in opening the database connection. And if the connection can't be opened in the first place, it's pointless having a "finally" block to close it.

    More ASP.NET Articles
    More By Harish Kamath (c) Melonfire


     

    ASP.NET ARTICLES

    - Disadvantages of the ASP.NET MVC Framework
    - Advantages of the ASP.NET MVC Approach
    - ASP.NET Web Forms Weaknesses
    - ASP.NET Web Forms Meets ASP.NET MVC
    - Source Code for Saving and Retrieving Data w...
    - Using GridView to Save and Retrieve Data wit...
    - Handling Dynamic Images in ASP.NET 3.5 AJAX ...
    - Retrieving Data with AJAX and the GridView C...
    - Playing with Images in ASP.NET 3.5 AJAX Appl...
    - Saving and Retrieving Data with AJAX
    - Enhancing PHP Via the ASP.NET AJAX Framework...
    - Enhancing PHP Programming with the ASP.NET A...
    - Classes and ASP.NET AJAX
    - Using ASP.NET AJAX
    - Building a Simple Storefront with LINQ

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




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