Home

The .NET Framework Support for Exception Handling

 

Exceptions in the .NET Framework

 

Introduction

To support exception handling, the .NET Framework provides a class named Exception. When an error is encountered, the Exception class allows you to identify the type of error and take an appropriate action. Exception mostly serves as the general class of exceptions. Because there are various types of errors that can occur on a web page, there are also many classes that are meant to handle their corresponding types of errors.

 

Practical LearningPractical Learning: Introducing .NET 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 geometry5b
  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:
      
    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
            {
                
            }
    }
  10. Save the file

The Exception's Message

Errors are dealt with in the catch section. On the right side of catch, open a parenthesis, declare a variable of the type of exception you want to deal with. By default, an exception is first of type Exception. Based on this, a typical formula to implement exception handling is:

try
{
    // Process the normal flow of the program here
}
catch(Exception e)
{
    // Deal with the exception here
}

When an exception occurs in the try section, code compilation is transferred to the catch section. If you declare the exception as an Exception type, this class will identify the error. One of the properties of the Exception class is called Message. This property contains a string that describes the type of error that occurred. You can then access this Exception.Message property to display an error message if you want. 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(Exception ex)
    {
	lblMessage.Text = ex.Message;
    }
}
</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 web page:

Message

Custom Error Messages

As you can see, one of the strengths of the Exception.Message property is that it gives you a good indication of the type of error that occurred. Sometimes, the message provided by the Exception class is not clear enough. As an alternative, you can create your own message and display it to the user. 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();

	// If no error occurred, don't show any message
	lblMessage.Text = "";
    }
    catch(Exception ex)
    {
	lblMessage.Text = "The calculation was not carried because " +
                          "the value you entered for the side is invalid";
    }
}
</script>

Here is an example of testing the web page:

Message

You can also combine the Exception.Message message with your own message:

<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(Exception ex)
    {
	lblMessage.Text = "Error: " + ex.Message + " Contact the " +
			  "web master.";
    }
}
</script>

Here is an example of testing the web page:

Message

 

 

 
 
 
 

A Review of .NET Exception Classes

 

Introduction

The .NET Framework provides various classes to handle different types of exception. One of the ways you can use one of the classes of the .NET Framework is that, if you know for sure that a particular exception will be produced, pass its name to the catch() clause. You don't have to name the argument. Then, in the catch() section, display a custom message.

The FormatException Exception

Everything a web page visitor types into a web control is primarily a string and that you must convert it to the appropriate type before using it. Otherwise, you may receive an error. The error is of the FormatException class. Here is an example:

 
 

Normal Flow

The error produced was:

Error

To handle a FormatException exception on a web page, pass this class to a catch clause.

Practical LearningPractical Learning: Using the FormatException Class

  1. Change 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 (FormatException ex)
        {
            lblMessage.Text = ex.Message + 
    			  " You typed an invalid value for the side.";
        }
    }
  2. Press Ctrl + 5 to test the web page
  3. In the Side text box, type 44:28
  4. Click the Calculate button
     
    Message
  5. Return to your programming environment

The OverflowException Exception

When a value beyond the allowable range is asked to be stored in memory, the web page would produce an OverflowException exception. 

The ArgumentOutOfRangeException Exception

If a web page visitor types a value that cannot be converted into a valid date, the web page would produce an ArgumentOutOfRangeException exception. One way you can avoid this is to guide the user but still take appropriate actions.

The DivideByZeroException Exception

Division by zero is an operation to always avoid. If an attempt to divide a value by 0 is performed, the web page produces a DivideByZeroException exception.

   
 

Home Copyright © 2009-2016, FunctionX, Inc.