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  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
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

    - Adding Content to a Static ASP.NET Website
    - Building a Static ASP.NET Website in a Basic...
    - Develop Your First ASP.NET Website with Visu...
    - Run ASP.NET in Windows XP Home with Cassini ...
    - How to Test a Web Application
    - How to Add Code and Validation Controls to a...
    - Working in Source and Split Views to Build a...
    - How to Build a Web Form for a One-Page Web A...
    - How to Develop a One-Page Web Application
    - An ASP.NET Web Application in Action
    - Developing ASP.NET Web Applications
    - An Introduction to ASP.NET Web Programming
    - Introduction to the ADO.NET Entity Framework...
    - Completing an In-Text Advertising System und...
    - Programming an In-Text Advertising System un...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek