Home

Introduction to Exception Handling

 

Exceptions Fundamentals

 

Introduction

An exception is something bad that can happen when the code of a web page is run or executed.  There are various types of bad things that can happen. The more familiar you are about such problems and the more you prepare for them, the more likely you will create effective web pages. Both the C# language and the .NET Framework provide various means of dealing with errors.

The ability to deal with errors on a program is called exception handling.

Practical LearningPractical Learning: Introducing 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#.
    Change the name of the web site to geometry5a
  4. Click OK
  5. In the Solution Explorer, right-click Default.aspx and click Rename
  6. Change the name to index.aspx and press Enter
  7. Change the file 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">
    
    <style>
    .maintitle
    {
    	color: blue;
    	font-family: 'Times New Roman' , Garamond, Georgia, Serif;
    	text-align: center;
    	font-size: 24pt;
    	font-weight: bold;
    	text-decoration: none;
    }
    </style>
    <title>Geometry: Square</title>
    </head>
    <body>
        
    <table border="0" style="width: 500px">
      <tr>
        <td style="width: 100%">
          <p class="maintitle">Geometry: Square</p>
        </td>
      </tr>
    </table>
    
    &nbsp;
    
    <form id="frmSquare" method="post" runat="server">
    <div>
    
    <hr />
    
    <table>
      <tr>
        <td style="width: 100px">Side:</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">Perimeter:</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">Area:</td>
        <td style="width: 121px">
                        <asp:TextBox ID="txtArea"
                                     runat="server">
                                     </asp:TextBox></td>
        <td style="width: 100px"></td>
      </tr>
    </table>
    
    &nbsp;
    
    <table style="width:500px; text-align:center;">
      <tr>
        <td>
            <asp:Label ID="lblMessage" runat="server"></asp:Label>
        </td>
      </tr>
    </table>
        
    </div>
    </form>
    </body>
    </html>
  8. In the lower-left section of the window, click the Design button and, on the form, double-click the Calculate button
  9. Implement the event as follows:
     
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void btnCalculate_Click(object sender,
                                          EventArgs e)
        {
            double side = 0.00;
            double perimeter, area;
    
            side = double.Parse(txtSide.Text);
            perimeter = side * 4;
            area = side * side;
    
            txtPerimeter.Text = perimeter.ToString();
            txtArea.Text = area.ToString();
        }
    }
  10. To execute the application, on the main menu, click Debug -> Start Without Debugging
  11. In the Side text box, type 44:28
     
    Square
  12. Click Calculate
     
    Square
  13. Return to your programming environment
 
 
 

Exceptional Behaviors

Consider the following code:

<%@ Page Language="C#" %>
<html>
<head>

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

    side = double.Parse(txtSide.Text);
    perimeter = side * 4;
    area = side * side;

    txtPerimeter.Text = perimeter.ToString();
    txtArea.Text = area.ToString();
}
</script>
 
 

 

<title>Exercise</title>
</head>
<body>

<form id="frmExercise" runat="server">
<table>
  <tr>
    <td></td>
    <td><h3>Square Evaluation</h3></td>
    <td></td>
  </tr>
  <tr>
    <td>Side:</td>
    <td><asp:TextBox id="txtSide" runat="server"></asp:TextBox></td>
    <td><asp:Button id="btnCalculate"
		    Text="Calculate"
		    OnClick="btnCalculateClick"
		    runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Perimeter:</td>
    <td><asp:TextBox id="txtPerimeter" runat="server"></asp:TextBox></td>
    <td></td>
  </tr>
  <tr>
    <td>Area:</td>
    <td><asp:TextBox id="txtArea" runat="server"></asp:TextBox></td>
    <td></td>
  </tr>
</table>
</form>

</body>
</html>

Here is an example of using the web page:

Normal Flow

Normally, the user should enter a number in the Side text box and click Calculate. But so more reason, a user may enter a bad value. Here is an example:

Normal Flow

Then:

Error

To handle an exception in your code, the formula to follow is:

try
{
    // Try the program flow
}
catch
{
    // Catch the exception
}

You start with a section that uses the try keyword. This section has an opening and a closing curly brackets that constitute its body. In the body of the try block, write the normal code this section is supposed to deal with. 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);
	perimeter = side * 4;
    	area = side * side;

    	txtPerimeter.Text = perimeter.ToString();
    	txtArea.Text = area.ToString();
    }
}
</script>

Under the try block, create a new block that uses the catch keyword and has a body delimited by an opening and a curly brackets. You must always have a catch section. That is, a try block cannot be used alone. 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);
	perimeter = side * 4;
    	area = side * side;

    	txtPerimeter.Text = perimeter.ToString();
    	txtArea.Text = area.ToString();
    }
    catch
    {
    }
}
</script>

Here is how this works. In the try block, the normal code is run. If there is a problem, the execution stops in the try block and gets out of it. Then it starts looking for a catch section, which we created. The catch section takes over.

Practical LearningPractical Learning: Handling Exceptions

  1. Change the code in the index.aspx.cs 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
            {
            }
    }
  2. Save the file
  3. Return to the browser and refresh
     
    Square
  4. Return to your programming environment

Exceptions and Custom Messages

If an error occurs when the code in  the try section executes, the execution is transferred to the next catch section. You can then use the catch section to deal with the error. At a minimum, you can display a message to inform the user. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>

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

    try {
    	side = double.Parse(txtSide.Text);
	perimeter = side * 4;
    	area = side * side;

    	txtPerimeter.Text = perimeter.ToString();
    	txtArea.Text = area.ToString();

	// If no error occurred, don't show any message
	lblMessage.Text = "";
    }
    catch
    {
	lblMessage.Text = "There was a problem with the program";
    }
}
</script>

<title>Exercise</title>
</head>
<body>

<form id="frmExercise" runat="server">
<table>
  <tr>
    <td></td>
    <td><h3>Square Evaluation</h3></td>
    <td></td>
  </tr>
  <tr>
    <td>Side:</td>
    <td><asp:TextBox id="txtSide" runat="server"></asp:TextBox></td>
    <td><asp:Button id="btnCalculate"
		    Text="Calculate"
		    OnClick="btnCalculateClick"
		    runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Perimeter:</td>
    <td><asp:TextBox id="txtPerimeter" runat="server"></asp:TextBox></td>
    <td></td>
  </tr>
  <tr>
    <td>Area:</td>
    <td><asp:TextBox id="txtArea" runat="server"></asp:TextBox></td>
    <td></td>
  </tr>
</table>
&nbsp;
<table>
  <tr>
    <td><asp:Label id="lblMessage" runat="server"></asp:Label></td>
  </tr>
</table>
</form>

</body>
</html>

  Here is an example of testing the page:

Normal Flow

Then:

Error

Practical LearningPractical Learning: Displaying Custom Messages

  1. To display a custom message, change the code of 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
            {
                lblMessage.Text = "You typed an invalid value for the side.";
            }
    }
  2. Save the file
  3. Return to the browser and refresh
     
    Square
  4. Return to your programming environment
 
   
 

Home Copyright © 2008-2016, FunctionX, Inc.