Home

Techniques of Handling Exceptions

 

Techniques of Catching Exceptions

 

Introduction

The Exception class is equipped with a Message property that holds a string about the error that occurred. The message of this property may not be particularly useful to a user. Fortunately, you can create your own message and pass it to the Exception class. To be able to receive custom messages, the Exception class provides the following constructor:

public Exception(string message);

Besides using this class or one of its derived classes in a catch clause, you can call this constructor to give a new and customized implementation of the exception.

Practical LearningPractical Learning: Introducing Techniques of Exceptions

  1. Start Microsoft Visual Studio or Microsoft Visual Web Developer
  2. To create a web site, on the main menu, click File -> New -> Web Site... (or File -> New Web Site)
  3. Make sure the Language combo box is set to Visual C#.
    Click the combo box on the left side of Browse, press End, and press Delete a few times to delete the default name of the web site
  4. Change it to geometry5
  5. Click OK
  6. In the Solution Explorer, right-click C:\...\geometry4\ and click New Folder
  7. Type images as the name of the new folder and press Enter
  8. Copy each of the following pictures to your My Documents folder:
     
    Rectangle Square
  9. On the main menu, click Web Site -> Add Existing Item...
  10. Locate the folder where you saved the pictures, select each and press Enter
  11. In the Solution Explorer, right-click Default.aspx and click Rename
  12. Change the name to index.aspx and press Enter
  13. To create a CSS file, on the main menu, click Web Site -> Add New Item...
  14. In the Templates list, click Style Sheet
  15. Set the name to geometry and press Enter
  16. Enter the following code in the file:
     
    body
    {
    	font-size: 11pt;
    	color: black;
    	font-family: Verdana, Tahoma, Arial, Sans-Serif;
    }
    
    hr { color: #0000ff }
    
    .maintitle
    {
    	color: blue;
    	font-family: 'Times New Roman' , Garamond, Georgia, Serif;
    	text-align: center;
    	font-size: 24pt;
    	font-weight: bold;
    	text-decoration: none;
    }
    
    .parajust
    {
    	font-family: Verdana, Tahoma, Arial, Sans-Serif;
    	font-size: 10pt;
    	font-weight: normal;
    	text-align: justify;
    }
    
    .centeredtext
    {
    	font-family: Verdana, Tahoma, Arial, Sans-Serif;
    	font-size: 10pt;
    	font-weight: normal;
    	text-align: center;
    }
    
    .centered
    {
    	text-align: center;
    }
    
    .formula
    {
    	font-weight: bold;
    	font-size: 10pt;
    	color: blue;
    	font-family: Verdana, Helvetica, Tahoma, Sans-Serif;
    }
    
    a:link       {
      font-family: Verdana, Helvetica, Arial, Sans Serif;
      color: #0000FF;
      font-size: 10pt;
      font-weight: bold;
      text-decoration: none }
    
    a:alink {
      font-family: Verdana, Helvetica, Arial, Sans Serif;
      color: #FF00FF;
      font-size: 10pt;
      font-weight: bold;
      text-decoration: none }
    
    a:visited
    {
    	font-family: Verdana, Helvetica, Arial, Sans Serif;
    	color: Green;
    	font-size: 10pt;
    	font-weight: bold;
    	text-decoration: none;
    }
    
    a:hover
    {
    	font-family: Verdana, Helvetica, Arial, Sans Serif;
    	color: #FF0000;
    	font-size: 10pt;
    	font-weight: Bold;
    	text-decoration: none;
    }
  17. To add a new web page, on the main menu, click Web Site -> Add New Item...
  18. Make sure Web Form is selected.
    Set the Name to rectangle and click Add
  19. Change the file as follows:
     
    <%@ Page Language="C#" 
             AutoEventWireup="true" 
             CodeFile="rectangle.aspx.cs" 
             Inherits="rectangle" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
    
    <link rel="Stylesheet" type="text/css" href="geometry.css" />
    <title>Geometry: Rectangle</title>
    
    </head>
    <body>
    
    <form id="frmRectangle"
          runat="server" 
          method="get" 
          action="rectangle.aspx">
        <div>
    <table border="0" style="width: 660px">
      <tr>
        <td style="width: 100%">
          <p class="maintitle">Geometry: Rectangle</p>
        </td>
      </tr>
    </table>
        
     &nbsp;
     
    <table border="0" width="660">
      <tr>
        <td>
          <p class="parajust">A rectangle is a geometric figure made 
          of 4 sides connected to produce four right angles. The 
          horizontal measurement of the rectangle, the base, is its 
          length. The vertical measurement of the figure is referred 
          to as its height. In geometry, a rectangle can be 
          represented as follows:</p>
            
          <p class="centered">
            <img src="images/rectangle.gif" alt="Rectangle" />
          </p>        
    
          <p class="parajust">To process a rectangle, you usually 
          must provide, or must be given, the length and the height. 
          You can then calculate the perimeter and the area. To 
          assist you with these calculations, you can use some 
          pre-established formulas. Suppose the values are 
          represented as follows:</p>
        </td>
      </tr>
    </table>
        
    &nbsp;
            
    <table style="width: 660px">
      <tr>
        <td style="width: 660px">
          <strong>L: length</strong>
        </td>
      </tr>
      <tr>
        <td style="width: 660px">
          <strong>H: height</strong>
        </td>
      </tr>
      <tr>
        <td style="width: 660px">
          <strong>P: perimeter</strong>
        </td>
      </tr>
      <tr>
        <td style="width: 660px">
          <strong>A: area</strong>
        </td>
      </tr>
    </table>
                
    &nbsp;
    
    <table border="0" style="width: 660px">
      <tr>
        <td style="width: 100%">
          <p class="parajust">Based on these, the following 
          calculations can be made</p>
        </td>
      </tr>
      <tr>
        <td style="width: 100%">
          <p class="formula">P = (L + H) * 2</p>
        </td>
      </tr>
      <tr>
        <td style="width: 100%">
          <p class="formula">A = L * H</p>
        </td>
      </tr>
    </table>
    
    <hr />
            <table>
                <tr>
                    <td style="width: 100px">
                        <asp:Label ID="Label1" 
                                   runat="server" 
                                   Text="Length:">
                        </asp:Label></td>
                    <td style="width: 121px">
                        <asp:TextBox ID="txtLength" 
                                     runat="server">
                        </asp:TextBox></td>
                    <td style="width: 100px">
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        <asp:Label ID="Label2" 
                                   runat="server" 
                                   Text="Height:">
                        </asp:Label></td>
                    <td style="width: 121px">
                        <asp:TextBox ID="txtHeight"
                                     runat="server">
                        </asp:TextBox></td>
                    <td style="width: 100px">
                        <asp:Button ID="btnCalculate"
                                    runat="server" 
                                    Text="Calculate" /></td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        <asp:Label ID="Label3"
                                   runat="server"
                                   Text="Perimeter:">
                        </asp:Label></td>
                    <td style="width: 121px">
                        <asp:TextBox ID="txtPerimeter"
                                     runat="server">
                        </asp:TextBox></td>
                    <td style="width: 100px">
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        <asp:Label ID="Label4"
                                   runat="server"
                                   Text="Area:">
                        </asp:Label></td>
                    <td style="width: 121px">
                        <asp:TextBox ID="txtArea"
                                     runat="server">
                        </asp:TextBox></td>
                    <td style="width: 100px">
                    </td>
                </tr>
            </table>
    
    <table border="0" width="660">
      <tr>
        <td colspan="2">
          <hr />
          
            &nbsp;</td>
      </tr>
      <tr>
        <td align="center" style="height: 18px">
          <a href="index.aspx">Home</a>
        </td>
        <td align="center" style="height: 18px">
          <p class="centered">Copyright © 2009 NetConsulting, Inc.</p>
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <hr />
        </td>
      </tr>
    </table>
        
        </div>
        </form>
    </body>
    </html>
  20. In the lower section, click Design
  21. Double-click the Calculate button and implement its event as follows:
     
    protected void btnCalculate_Click(object sender, EventArgs e)
    {
            double length = 0.00;
            double height = 0.00;
            double perimeter;
            double area;
    
            length = double.Parse(txtLength.Text);
            height = double.Parse(txtHeight.Text);
    
            perimeter = (length + height) * 2;
            area = length * height;
    
            txtPerimeter.Text = perimeter.ToString();
            txtArea.Text = area.ToString();
    }
  22. To add a new web page, on the main menu, click Web Site -> Add New Item...
  23. Make sure Web Form is selected.
    Set the Name to square and click Add
  24. Change the file as follows:
     
    <%@ Page Language="C#"
             AutoEventWireup="true" 
             CodeFile="square.aspx.cs" 
             Inherits="square" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
    
    <link rel="Stylesheet" type="text/css" href="geometry.css" />
    
    <title>Geometry: Square</title>
    </head>
    <body>
    
        <form id="frmSquare" runat="server" method="post">
        <div>
        
    <table border="0" style="width: 660px">
      <tr>
        <td style="width: 100%">
          <p class="maintitle">Geometry: Square</p>
        </td>
      </tr>
    </table>
    
    &nbsp;
    
    <table border="0" width="660">
      <tr>
        <td>
          <p class="parajust">A square is a type of 
          <a href="rectangle.aspx">rectangle</a> 
          for which all 4 sides are equal. This means that the horizontal 
          measurement, the base or length and the height are equal. The 
          length of each side is then called the side of the square. A 
          square can be represented as follows:</p>
                    
          <p class="centered"><img src="images/square.gif" alt="Square" />
          </p>
                    
          <p class="parajust">To process a square, you must have the 
          measure of the side. This would allow you to calculate the 
          perimeter and the area. To do this, you can use simple 
          geometric formulas. Consider the following:</p>
          </td>
      </tr>
    </table>
    
    &nbsp;
    
    <table>
      <tr>
        <td style="width: 660px">
          <strong>S: side</strong>
        </td>
      </tr>
      <tr>
        <td style="width: 660px">
          <strong>P: perimeter</strong>
        </td>
      </tr>
      <tr>
        <td style="width: 660px">
          <strong>A: area</strong>
        </td>
      </tr>
    </table>
    
    &nbsp;
    
    <table border="0" style="width: 660px">
      <tr>
        <td style="width: 100%">
          <p class="parajust">To calculate the values of a square, you can 
          use the following formulas:</p></td>
      </tr>
      <tr>
        <td style="width: 100%">
          <p class="formula">P = S * 4</p>
        </td>
      </tr>
      <tr>
        <td style="width: 100%">
          <p class="formula">A = S * S</p>
        </td>
      </tr>
    </table>
    
    <hr />
    
    <table>
      <tr>
        <td style="width: 100px">
          <asp:Label ID="Label1"
                     runat="server" 
                     Text="Side:"></asp:Label></td>
        <td style="width: 121px">
          <asp:TextBox ID="txtSide"
                       runat="server"></asp:TextBox></td>
        <td style="width: 100px">
          <asp:Button ID="btnCalculate" 
                      runat="server" 
                      Text="Calculate" /></td>
      </tr>
      <tr>
        <td style="width: 100px">
          <asp:Label ID="Label2"
                     runat="server" 
                     Text="Perimeter"></asp:Label></td>
        <td style="width: 121px">
          <asp:TextBox ID="txtPerimeter"
                       runat="server">
                        </asp:TextBox></td>
        <td style="width: 100px"></td>
      </tr>
      <tr>
        <td style="width: 100px">
                        <asp:Label ID="Label3"
                                   runat="server"
                                   Text="Area:"></asp:Label></td>
        <td style="width: 121px">
                        <asp:TextBox ID="txtArea"
                                     runat="server">
                                     </asp:TextBox></td>
        <td style="width: 100px"></td>
      </tr>
    </table>
    </div>
    </form>
    
    <table border="0" width="660">
      <tr>
        <td colspan="2">
          <hr />
        </td>
      </tr>
      <tr>
        <td align="center">
          <a href="index.aspx">
            <strong><span style="font-size: 10pt">Home</span></strong>
          </a>
        </td>
        <td align="center">
          <p class="centered">Copyright © 2009 NetConsulting, Inc.</p>
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <hr />
        </td>
      </tr>
    </table>
    
    </body>
    </html>
  25. In the lower-left section of the window, click the Design button and, on the form, double-click the Calculate button
  26. Change the file as follows:
     
    protected void btnCalculate_Click(object sender, EventArgs e)
    {
            double side = 0.00;
            double perimeter, area;
    
            try
            {
                side = double.Parse(txtSide.Text);
                perimeter = side * 4;
                area = side * side;
    
                txtPerimeter.Text = perimeter.ToString();
                txtArea.Text = area.ToString();
            }
            catch (FormatException ex)
            {
                lblMessage.Text = " You typed an invalid value for the side.";
            }
    }
  27. Click the index.aspx tab to access its file
  28. Change its content as follows:
     
    <%@ Page Language="C#"
             AutoEventWireup="true"
             CodeFile="index.aspx.cs" 
             Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    
    <link rel="Stylesheet" type="text/css" href="geometry.css" />
    
    <title>Geometry</title>
    </head>
    <body>
       
    <h3>Geometric Figures</h3>
    
    <p><a href="rectangle.aspx">Rectangle</a></p>
    <p><a href="square.aspx">Square</a></p>
    
    <table border="0" width="660">
      <tr>
        <td>
          <hr />
        </td>
      </tr>
      <tr>
        <td align="center" style="height: 18px">
          &nbsp;<p class="centered">Copyright © 2009 NetConsulting, Inc.</p>
        </td>
      </tr>
      <tr>
        <td>
          <hr />
        </td>
      </tr>
    </table>
        
    </body>
    </html>
  29. Save all
 
 
 
 

Throwing an Exception

When a bad behavior occurs in your application, the program is said to throw an exception. To customize the throwing of an exception, in the section of code where you are anticipating the error, type the throw keyword followed by a new instance of the Exception class (or one of its derived classes) using the constructor that takes a string. Here is an example:

<script runat="server">
private void btnCalculateClick(object sender, EventArgs e)
{
    double side;
    double perimeter, area;

    try {
    	side = double.Parse(txtSide.Text);
	
	throw new Exception(side.ToString());

	perimeter = side * 4;
    	area = side * side;

    	txtPerimeter.Text = perimeter.ToString();
    	txtArea.Text = area.ToString();
    }
    catch(Exception ex)
    {
	lblMessage.Text = "The value you typed, " + ex.Message + " is not valid.";
    }
}
</script>

In reality, to effectively throw an exception, you should write a conditional that specifies under what circumstance(s) the exception should be thrown.

Catching Various Exceptions

A function or a method with numerous or complex operations and requests can also produce different types of errors. To catch various exceptions, you can create different catch sections, each made for a particular error. The formula used would be:

try {
	// Code to Try
}
catch(Arg1)
{
	// One Exception
}
catch(Arg2)
{
	// Another Exception
}

This makes it to create a catch block for each type of exception. In the same way, you can write different throw expressions if the code can produce different types of errors.

Practical LearningPractical Learning: Catching Various Exceptions

  1. Click the square.aspx.cs tab
  2. To catch various exceptions, change the file as follows:
     
    protected void btnCalculate_Click(object sender, EventArgs e)
    {
            double side = 0.00;
            double perimeter, area;
    
            try
            {
                side = double.Parse(txtSide.Text);
                perimeter = side * 4;
                area = side * side;
    
                txtPerimeter.Text = perimeter.ToString();
                txtArea.Text = area.ToString();
            }
            catch(FormatException)
            {
                lblMessage.Text = "You typed an invalid value for the side.";
            }
            catch (Exception)
            {
                lblMessage.Text = "Something bad happened to the web page. " +
                                  "Contact the webmaster";
            }
    }
  3. Click the index.cs tab
  4. Press Ctrl + F5 to test the web site
  5. Click the Square link
  6. In the Side text box, type something
  7. Click Calculate
  8. Return to your programming environment

Nesting an Exception

You can create an exception inside of another. This is referred to as nesting an exception. To nest an exception, write a try block in the body of the parent exception. The nested try block must be followed by its own catch(es) clause. To effectively handle the exception, make sure you include an appropriate throw in the try block.

Practical LearningPractical Learning: Nesting Exceptions

  1. Click the square.aspx.cs tab
  2. To catch various exceptions, change the file as follows:
     
    protected void btnCalculate_Click(object sender, EventArgs e)
    {
        double length = 0.00;
        double height = 0.00;
        double perimeter;
        double area;
    
        try
        {
            try
            {
                length = double.Parse(txtLength.Text);
            }
            catch (FormatException)
            {
                lblMessage.Text = "You typed an invalid value for the length.";
            }
    
            try
            {
                height = double.Parse(txtHeight.Text);
            }
            catch (FormatException)
            {
                lblMessage.Text = "You typed an invalid value for the height.";
            }
    
            perimeter = (length + height) * 2;
            area = length * height;
    
            txtPerimeter.Text = perimeter.ToString();
            txtArea.Text = area.ToString();
        }
        catch
        {
            lblMessage.Text = "Something bad happened to the web page. " +
                              "Contact the webmaster";
        }
    }
  3. Save all
  4. Return to the browser and refresh
  5. Click the Rectangle link
  6. In the Length text box, type 42.60
  7. In the Height text box, type 35.85
     
    Rectangle
  8. Click Calculate
     
  9. Change the value in the Length text box to 42Period60
  10. Click Calculate
     
    Rectangle
  11. Return to your programming environment

Exceptions and Functions or Methods

One of the most effective techniques used to deal with code is to isolate assignments. Isolating assignments and handing them to method is an important matter in the area of application programming. One of the ways you can use functions or methods in exception routines is to have a central method that receives variables, and sends them to other external methods. The external method tests the value of a variable. If an exception occurs, the external method displays or sends a throw. This throw can be picked up by the method that sent the error.

Creating an Exceptional Class

The Exception class of the .NET Framework is a great tool for handling exceptions. To deal with particular errors, various classes are derived from Exception. If for some reason neither the Exception class nor any of the Exception-based classes fulfills your requirement, you can derive a new class from Exception or from one of the available Exception-based classes.

To derive a class from Exception or from one of its classes, simply follow the rules of class inheritance. Here is an example of a class based on Exception:

public class CustomException : Exception 
{
}

After deriving the class, you can add the necessary members as you see fit. Remember that the primary characteristic of an exception is to present a message to the user. In Exception-based classes, this message is represented by the Message property. Therefore, if you want to prepare a custom message for your class, you can override or new this property. Once you have created and customized your exceptional class, you can use it the same way you would another exception class, such as throwing it.

 
 
   
 

Home Copyright © 2009-2015, FunctionX, Inc.