Introduction to Exceptions

Overview

So far (in previous lessons), we have learned to perform various types of operations that involve numeric values. What we did so far was to avoid bad occurences. The reality is that bad occurrences are a reality of life. We need to learn how to deal with them so we can assist the users of our application when an error occurs in our application.

Practical LearningPractical Learning: Introducing Exception Handling

  1. Start Microsoft Visual Studio. Create a new ASP.NET Core Web App named TaxPreparation08 that supports the .NET 5.0 (Long-Term Support) and uncheck the Configure for HTTPS check box
  2. In the Solution Explorer, expand wwwroot
  3. In the Solution Explorer, under wwwroot, right-click css -> Add -> New Item...
  4. In the left list of the Add New Item dialog box, under Visual C#, expand ASP.NET Core. Expand Web, and click Content
  5. In the middle list, click Style Sheet
  6. Change the file Name to TaxPreparation
  7. Press Enter
  8. Change the document as follows:
    body {
    }
    
    .delimiter   { margin:           auto;
                   width:            450px;                  }
    .top-bar     { border-bottom:    6px solid blue;
                   background-color: #022d50 !important;     }
    .common-font { font-family:      Georgia, Garamond, 'Times New Roman', serif; }
    .navbar-light .navbar-brand       { color:       white;  }
    .navbar-light .navbar-brand:hover { color:       yellow; }
    .navbar-light .navbar-brand:focus { color:       khaki;  }
    .navbar-light .navbar-brand       { font-family: Georgia, Garamond, 'Times New Roman', serif; }
    .nav-link                         { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  9. In the Solution Explorer, under Pages, expand Shared
  10. In the Solution Explorer, under Pages and under Shared, double-click _Layout.cshtml
  11. Change the document as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - DeltaX Services</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/css/TaxPreparation.css" asp-append-version="true" />
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 top-bar">
                <div class="container">
                    <a class="navbar-brand" asp-area="" asp-page="/Index">DeltaX Home</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white" asp-area="" asp-page="/Privacy">Privacy</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                <p class="text-center common-font">&copy; 2022 - DeltaX Services - <a asp-area="" asp-page="/Privacy">Privacy</a></p>
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
  12. In the Solution Explorer, under Pages, double-click Index.cshtml to open it
  13. Change the document as follows:
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    @{
        /* New York State and New York City 
         * https://www.tax.ny.gov/pdf/current_forms/it/it2105i.pdf */
        string strNetPay = "0.00";
        string strTaxAmount = "0.00";
        double taxRateExcess = 0.00;
        double amountInExcess = 0.00;
        string strGrossSalary = "0.00";
    
        if (Request.HasFormContentType)
        {
            double excess;
            double taxAmount;
            double grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
    
            // Married Filing Jointly and Qualifying Widow(er)
            if(grossSalary is (>= 0.00) and (<= 17_150))
            {
                taxRateExcess = 4.00;
                amountInExcess = 0.00;
                taxAmount = grossSalary * 4.00 / 100.00;
            }
            else if(grossSalary is (> 17_150) and (<= 23_600))
            {
                taxRateExcess = 4.50;
                amountInExcess = 686;
                excess = (grossSalary - 17_150) * 4.5 / 100.00;
                taxAmount = excess + 686;
            }
            else if(grossSalary is (> 23_600) and (<= 27_900))
            {
                taxRateExcess = 5.25;
                amountInExcess = 976;
                excess = (grossSalary - 23_600) * 5.25 / 100.00;
                taxAmount = excess + 976;
            }
            else if(grossSalary is (> 27_900) and (<= 161_550))
            {
                taxRateExcess = 5.85;
                amountInExcess = 1_202;
                excess = (grossSalary - 27_900) * 5.85 / 100.00;
                taxAmount = excess + 1_202;
            }
            else if(grossSalary is (> 161_550) and (<= 323_200))
            {
                taxRateExcess = 6.25;
                amountInExcess = 9_021;
                excess = (grossSalary - 161_550) * 6.25 / 100.00;
                taxAmount = excess + 9_021;
            }
            else if(grossSalary is (> 323_200) and (<= 2_155_350))
            {
                taxRateExcess = 6.85;
                amountInExcess = 19_124;
                excess = (grossSalary - 323_200) * 6.85 / 100.00;
                taxAmount = excess + 19_124;
            }
            else if(grossSalary is (> 2_155_350) and (<= 5_000_000))
            {
                taxRateExcess = 9.65;
                amountInExcess = 144_626;
                excess = (grossSalary - 2_155_350) * 9.65 / 100.00;
                taxAmount = excess + 144_626;
            }
            else if(grossSalary is (> 5_000_000) and (<= 25_000_000))
            {
                taxRateExcess = 10.3;
                amountInExcess = 419_135;
                excess = (grossSalary - 5_000_000) * 10.3 / 100.00;
                taxAmount = excess + 419_135;
            }
            else // if(grossSalary is > 25_000_000)
            {
                taxRateExcess = 10.9;
                amountInExcess = 2_479_135;
                excess = (grossSalary - 25_000_000) * 10.9 / 100.00;
                taxAmount = excess + 2_479_135;
            }
    
            strGrossSalary = $"{grossSalary:F}";
            strTaxAmount = $"{taxAmount:F}";
            strNetPay = $"{(grossSalary - taxAmount):F}";
        }
    }
    
    <h1 class="text-center common-font">- DeltaX - Tax Preparation Services -</h1>
    <hr />
    <h2 class="text-center common-font">- New York State - State Income Tax -</h2>
    <hr />
    <div class="delimiter common-font">
        <form name="frmTaxPreparation" method="post">
            <table class="table common-font">
                <tr>
                    <td width="150">@Html.Label("txtGrossSalary", "Gross Salary:", new { @class = "" })</td>
                    <td>@Html.TextBox("txtGrossSalary", @strGrossSalary, new { @class = "form-control" })</td>
                </tr>
                <tr>
                    <td></td>
                    <td class="pcenter"><input type="submit" value="Evaluate Taxes" class="btn-primary" /></td>
                </tr>
            </table>
        </form>
        
        <table class="table">
            <tr>
                <td width="250">Gross Salary:</td>
                <td>@strGrossSalary</td>
            </tr>
            <tr>
                <td>Tax Rate in Excess:</td>
                <td>@taxRateExcess%</td>
            </tr>
            <tr>
                <td>Amount Added in Excess:</td>
                <td>@amountInExcess</td>
            </tr>
            <tr>
                <td>Tax Amount from Income:</td>
                <td>@strTaxAmount</td>
            </tr>
            <tr>
                <td>Net Pay:</td>
                <td>@strNetPay</td>
            </tr>
        </table>
    </div>
  14. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Exception Handling

  15. Click the Gross Salary text box and type 6484.85
  16. Click the Evaluate Taxes button:

    Introduction to Exception Handling

  17. Change the Gross Salary to 18374.66 and click the Evaluate Taxes button:

    Introduction to Exception Handling

  18. Return to your programming environment

Exceptional Behaviors

An exception is an unusual situation that could occur in your project. As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results. The ability to deal with a program's eventual abnormal behavior is called exception handling. C# provides many keywords to deal with an exception:

  1. Trying the normal flow: To deal with the expected behavior of a program, use the try keyword as in the following formula:
    try {behavior}
    The try keyword is required. It lets the compiler know that you are attempting a normal flow of your program. The actual behavior that needs to be evaluated is included between an opening curly bracket "{" and a closing curly bracket "}". Inside the brackets, implement the normal flow that the program must follow, at least for this section of the code. Here is an example:
    double number, result;
    
    try 
    {
        number = double.Parse(Request.Form["txtNumber"]);
        result = number * 2.00;
    }
  2. Catching Errors: During the flow of the program as part of the try section, if an abnormal behavior occurs, instead of letting the webpage display an error, you can transfer the flow of the code to another section that can deal with it. The syntax used by this section is:
    catch {what-to-do}
    This section always follows the try section. There must not be any code between the try's closing bracket and the catch section. The catch keyword is required and follows the try section. Combined with the try block, the syntax of an exception would be:
    try
    {
        // Try the program flow
    }
    catch
    {
        // Catch the exception
    }

Exceptions and Custom Messages

As mentioned already, if an error occurs when processing the code in the try section, the compiler transfers the processing 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
@model PracticalLearning.Pages.ExceptionHandlingModel
@{
    string strMessage = "";
    double number = 0.00, result = 0.00;

    if (Request.HasFormContentType)
    {
        try
        {
            number = double.Parse(Request.Form["txtNumber"]);
            result = number * 2.00;
        }
        catch
        {
            strMessage = "The value you entered is not a valid number.";
        }
    }
}

<form method="post" name="frmNumbers">
    <table style="width: 300px" align="center">
        <tr>
            <td style="width: 150px">Number:</td>
            <td><input type="text" id="txtNumber" value="@number" style="width: 345px" /></td>
        </tr>
    </table>

    <table style="width: 300px" align="center">
        <tr>
            <td style="width: 50px">&nbsp;</td>
            <td><input type="submit" value="Add" name="btnCalculate" style="width: 150px" /></td>
        </tr>
    </table>

    <table style="width: 300px" align="center">
        <tr>
            <td style="width: 150px">Result:</td>
            <td><input type="text" id="txtResult" value="@result" style="width: 100px" /> %</td>
        </tr>
    </table>
</form>

Introduction to Exceptions in the .NET Library

The Exception Class

To support exception handling, the .NET library provides a special class called Exception. Once the compiler encounters an error, the Exception class allows you to identify the type of error and take an appropriate action.

Normally, Exception mostly serves as the general class of exceptions. Anticipating various types of problems that can occur in a program, Microsoft derived various classes from Exception to make this issue friendlier. As a result, almost any type of exception you may encounter already has a class created to deal with it.

In exception handling, errors are dealt with in the catch section. Therefore, use catch as if it were a method. This means that, on the right side of catch, add some parentheses. In the parentheses, pass a parameter 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
}

The Message of an Exception

When an exception occurs in the try section, code compilation is transferred to the catch section. If you pass 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 is of type string. It describes the type of error that occurred. You can then use this Exception.Message property to display an error message if you want.

Introduction to Custom Error Messages

One of the strengths of the Exception.Message property is that it gives you a good indication of the type of problem that occurred. Sometimes, the message provided by the Exception class may not appear explicit enough. In fact, you may not want to show it to the visitor because, in some cases, the user may not understand what the expression "correct format" means and why it is being used. As an alternative, you can create your own message and display it to the user. One way to do this is to create a message box in a catch clause. Here is an example:

double number, result;

try {
    number = double.Parse(ReadLine());
    result = number * 2.00;
}
catch(Exception exc)
{
    strMessage = "The operation could not be carried because " +
                    "the number you typed is not valid";
}

If you use the above technique, in some cases, the C# compiler, or some C# compilers, may present a warning because you didn't use the argument. To address this issue, you have various options. You can pass the parameter as an underscore and not use that underscore in the catch section (but you may receive the same warning as previously). Here is an example:

void Calculate()
{
    try
    {
    }
    catch(Exception _)
    {
        strMessage = " The value you entered for the amount to allocate " +
                     "or pledge is not valid. Only natural numbers " +
                     "(such as 200, 1250, 5000, or 100000) are allowed.";
    }
}

You can use only the message of the argument as seen earlier:

void Calculate()
{
    try
    {
    }
    catch(Exception exc)
    {
        strMessage = exc.Message;
    }
}

You can combine the Exception.Message message and your own message. Here is an example:

void Calculate()
{
    try
    {
    }
    catch(Exception exc)
    {
       strMessage = exc.Message +
                        " The value you entered for the amount to allocate " +
                        "or pledge is not valid. Only natural numbers " +
                        "(such as 200, 1250, 5000, or 100000) are allowed.";
    }
}

The last, sometimes the best, solution is to not name the parameter. Here is an example:

void Calculate()
{
    try
    {
    }
    catch(Exception)
    {
        strMessage = " The value you entered for the amount to allocate " +
                        "or pledge is not valid. Only natural numbers " +
                        "(such as 200, 1250, 5000, or 100000) are allowed.",;
    }
}

In some cases, you will want to create a custom error message but send it to another section of the project. To assist you with this, the Exception class with equipped with a constructor that takes a string as argument.

A Custom Exception Class

You can create your own class to deal with exceptions in your project, and you can create such a class from scratch. Instead of going through such a complicated adventure, a better alternative is derive a class from Exception. Here is an example:

public class UnwantedBehavior : Exception
{
}

By tradition, a class that derives from Exception must have a name that ends with Exception. Here is an example:

public class UnwantedBehaviorException : Exception
{
}

To assist you with exceptions, the .NET library provides a rich collection of classes for exceptions. Therefore, before creating your own exception class, first find out if there is already an exception class that provides the behavior you want, and use that built-in class.

Introduction to Built-In Exception Classes

Overview

The .NET library provides various classes to handle almost any type of exception. When your application produces an error, the compiler will display a message to notify the user.

To identify the primary class that deals with the exception, click the Details button.

There are two main ways you can use one of the classes of the .NET library. If you know that a particular exception will be produced, pass its name to a catch() clause. You don't have to name the argument. Then, in the catch section, display a custom message.

The Format Exception

Everything the user types into an application using the keyboard is primarily a string and you must convert it to the appropriate type before using it. When you request a specific type of value from the user, after the user has typed it and you decide to convert it to the appropriate type, if your conversion fails, the compiler produces an error. The error is of a class named FormatException.

Here is a program that deals with a FormatException exception:

double number, result;

try {
    WriteLine("Number:");
    number = double.Parse(Request[]);
    result = number * 2.00;
}
catch(FormatException exc)
{
    strMessage = "The value you entered is not a valid number.";
}

Practical LearningPractical Learning: Handling an Exception

  1. Change the Index.cshtml code as follows:
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    @{
        /* New York State and New York City 
         * https://www.tax.ny.gov/pdf/current_forms/it/it2105i.pdf */
        string? strMessage = null;
        string strNetPay = "0.00";
        string strTaxAmount = "0.00";
        double taxRateExcess = 0.00;
        double amountInExcess = 0.00;
        string strGrossSalary = "0.00";
    
        if (Request.HasFormContentType)
        {
            double excess;
            double taxAmount = 0.00;
            double grossSalary = 0.00;
    
            try
            {
                grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
    
                // Married Filing Jointly and Qualifying Widow(er)
                if (grossSalary is (>= 0.00) and (<= 17_150))
                {
                    taxRateExcess = 4.00;
                    amountInExcess = 0.00;
                    taxAmount = grossSalary * 4.00 / 100.00;
                }
                else if (grossSalary is (> 17_150) and (<= 23_600))
                {
                    taxRateExcess = 4.50;
                    amountInExcess = 686;
                    excess = (grossSalary - 17_150) * 4.5 / 100.00;
                    taxAmount = excess + 686;
                }
                else if (grossSalary is (> 23_600) and (<= 27_900))
                {
                    taxRateExcess = 5.25;
                    amountInExcess = 976;
                    excess = (grossSalary - 23_600) * 5.25 / 100.00;
                    taxAmount = excess + 976;
                }
                else if (grossSalary is (> 27_900) and (<= 161_550))
                {
                    taxRateExcess = 5.85;
                    amountInExcess = 1_202;
                    excess = (grossSalary - 27_900) * 5.85 / 100.00;
                    taxAmount = excess + 1_202;
                }
                else if (grossSalary is (> 161_550) and (<= 323_200))
                {
                    taxRateExcess = 6.25;
                    amountInExcess = 9_021;
                    excess = (grossSalary - 161_550) * 6.25 / 100.00;
                    taxAmount = excess + 9_021;
                }
                else if (grossSalary is (> 323_200) and (<= 2_155_350))
                {
                    taxRateExcess = 6.85;
                    amountInExcess = 19_124;
                    excess = (grossSalary - 323_200) * 6.85 / 100.00;
                    taxAmount = excess + 19_124;
                }
                else if (grossSalary is (> 2_155_350) and (<= 5_000_000))
                {
                    taxRateExcess = 9.65;
                    amountInExcess = 144_626;
                    excess = (grossSalary - 2_155_350) * 9.65 / 100.00;
                    taxAmount = excess + 144_626;
                }
                else if (grossSalary is (> 5_000_000) and (<= 25_000_000))
                {
                    taxRateExcess = 10.3;
                    amountInExcess = 419_135;
                    excess = (grossSalary - 5_000_000) * 10.3 / 100.00;
                    taxAmount = excess + 419_135;
                }
                else // if(grossSalary is > 25_000_000)
                {
                    taxRateExcess = 10.9;
                    amountInExcess = 2_479_135;
                    excess = (grossSalary - 25_000_000) * 10.9 / 100.00;
                    taxAmount = excess + 2_479_135;
                }
            }
            catch (FormatException fexc)
            {
                strMessage = "It appears that you didn't provide a valid value for the gross salary. The message produced is " +
                             System.Environment.NewLine + fexc.Message;
            }
    
            strGrossSalary = $"{grossSalary:F}";
            strTaxAmount = $"{taxAmount:F}";
            strNetPay = $"{(grossSalary - taxAmount):F}";
        }
    }
    
    <h1 class="text-center common-font">- DeltaX - Tax Preparation Services -</h1>
    <hr />
    <h2 class="text-center common-font">- New York State - State Income Tax -</h2>
    <hr />
    <div class="delimiter common-font">
        <form name="frmTaxPreparation" method="post">
            <table class="table common-font">
                <tr>
                    <td width="150">@Html.Label("txtGrossSalary", "Gross Salary:", new { @class = "" })</td>
                    <td>@Html.TextBox("txtGrossSalary", @strGrossSalary, new { @class = "form-control" })</td>
                </tr>
                <tr>
                    <td></td>
                    <td class="pcenter"><input type="submit" value="Evaluate Taxes" class="btn-primary" /></td>
                </tr>
            </table>
        </form>
        
        <table class="table">
            <tr>
                <td width="250">Gross Salary:</td>
                <td>@strGrossSalary</td>
            </tr>
            <tr>
                <td>Tax Rate in Excess:</td>
                <td>@taxRateExcess%</td>
            </tr>
            <tr>
                <td>Amount Added in Excess:</td>
                <td>@amountInExcess</td>
            </tr>
            <tr>
                <td>Tax Amount from Income:</td>
                <td>@strTaxAmount</td>
            </tr>
            <tr>
                <td>Net Pay:</td>
                <td>@strNetPay</td>
            </tr>
        </table>
    
        <p>@strMessage</p>
    </div>
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. If the browser presents a Resend button, click it. Otherwise, refresh the browser
  4. Delete the value in the Gross Salary text box and click the Evaluate Taxes button:

    Introduction to Exception Handling

  5. Change the Gross Salary to 26197.53 and click the Evaluate Taxes button:

    Introduction to Exception Handling

  6. Return to your programming environment

The Overflow Exception

An application receives, processes, and produces values on a regular basis. To better manage these values, as we saw when studying variables and data types in previous lessons, the compiler uses appropriate amounts of space to store its values. If you provide a value higher than the data type allows, you would get an error.

When a value beyond the allowable range is asked to be stored in memory, the compiler produces an error of a class named OverflowException.

The Argument Out of Range Exception

If the user provides a value that is outside a range allowed by its type or class and therefore cannot be converted appropriately, the compiler produces an exception of a class named ArgumentOutOfRangeException.

The Divide by Zero Exception

If your application tries to divide a number by 0, the compiler produces an error of a class named DivideByZeroException.

Throwing an Exception

Introduction

As mentioned previously, the Exception class is equipped with a Message property that carries a message for the error that occurred. We also mentioned that the message of this property may not be particularly useful to a user. Fortunately, you can create your own message and pass it to an Exception object. To be able to receive custom messages, the Exception class provides the following constructor:

public Exception(string message);

As mentioned already, all exceptions classes derive directly or indirectly from Exception. As a result, all those classes are equipped with a default constructor and all of them inherit the constructor that takes a string as argument.

To use the constructor that uses a string parameter, in the section in which you are anticipating the error, use a keyword named throw. Follow this keyword by the new operator to instantiate the Exception class using this constructor. Here is an example:

@page
@model TaxPreparation08.Pages.ExceptionsModel
@{
    string message = "";
    double result = 0.00;
    string oper = "";
    double number1 = 0.00, number2 = 0.00;


    if (Request.HasFormContentType)
    {
        try
        {
            number1 = double.Parse(Request.Form["txtNumber1"]);
            number2 = double.Parse(Request.Form["txtNumber2"]);
            oper = Request.Form["txtNumber2"];

            if( (oper != "+") && (oper != "-") && (oper != "*") && (oper != "/") )
            {
                throw new Exception(oper);
            }

            switch (oper)
            {
                case "+":
                    result = number1 + number2;
                    break;
                case "-":
                    result = number1 - number2;
                    break;
                case "*":
                    result = number1 * number2;
                    break;
                case "/":
                    result = number1 / number2;
                    break;
                default:
                    message = "Bad Operation";
                    break;
            }

        }
        catch (Exception exc)
        {
            message = "The value you entered is not a valid number. Please report the error as: " +
                      Environment.NewLine + exc.Message;
        }
    }
}

<h3>Elementary Algebra</h3>

@using (Html.BeginForm())
{
    <table>
        <tr>
            <td>Number 1:</td>
            <td>@Html.TextBox("txtNumber1", @number1)</td>
        </tr>
        <tr>
            <td>Operator:</td>
            <td>@Html.TextBox("txtOperator", @oper)</td>
        </tr>
        <tr>
            <td>Number 2:</td>
            <td>@Html.TextBox("txtNumber2", @number1)</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnCalculate" value="Calculate" /></td>
        </tr>
        <tr>
            <td>Result:</td>
            <td>@Html.TextBox("txtResult", @result)</td>
        </tr>
    </table>

    <p>@message</p>
}

Exceptions and Methods

There are various ways you can involve exceptions in a function or method. When it comes to functions and methods, one way you can use the throw option is to get out of the function or method at any time, for any reason. Consider the following code:

using System;

class Exercise
{
    public void ShowMessage()
    {
        throw new Exception();
    }
}

In this example, the line that holds the message box will never be reached. One way you can proceed in a function or method is to throw an exception if something happens. That is, you can create a conditional statement that would consider, or throw an exception.

Exceptions and Properties

If you create a non-automatic property that processes some data and returns a valid result, if there is a possibility that something could go wrong in the calculation, you can make the property throw an exception. You can perform some procesing in the set clause of the property. In that clause, you can throw an exception. Here is an example:

using System;

public class WorkDay
{
    private double tw;

    public WorkDay(double time)
    {
        tw = time;
    }

    public double TimeWorked
    {
        get
        {
            return tw;
        }
        set
        {
            if (tw > 24)
                throw new FormatException("Nobody can work more than 24 hours in one day.");

            tw = value;
        }
    }
}

Or you can handle the exception in the get clause.

Topics on Handling Exceptions

Catching Various Exceptions

In the above examples, when we anticipated some type of problem, we instructed the compiler to use our default catch section. We left it up to the compiler to find out when there was a problem and we provided a catch section to deal with it. A secttion of code with numerous or complex operations and requests can also produce different types of errors. You should be able to face different problems and deal with them individually, each by its own kind. To do this, you can create different catch sections, each made for a particular error. The formula to follow is:

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

The compiler would proceed from top-down:

  1. Following the normal flow of the program, the compiler enters the try block
  2. If no exception occurs in the try block, the rest of the try block executes.
    If an exception occurs in the try block, the compiler registers the type of error that occurred. If there is a throw line, the compiler registers it also:
    1. The compiler gets out of the try section
    2. The compiler examines the first catch section. If the first catch clause matches the thrown error, that catch section executes and the exception handling routine may end. If the first catch doesn't match the thrown error, the compiler proceeds with the next catch clause
    3. The compiler checks the next match, if any, and proceeds as in the first catch. This continues until the compiler finds a catch clause that matches the thrown error
    4. If one of the catch clauses matches the thrown error, its body executes. If no catch clause matches the thrown error, the compiler calls the Exception class and uses the default message

Multiple catch clauses are written if or when a try block is expected to throw different types of errors. For example, in our calculator, we want to consider only the addition, the subtraction, the multiplication, and the division. It is also likely that the user may type one or two invalid numbers. This leads us to know that our project can produce at least two types of errors. Based on this, we can address them using two catch clauses. Here is an example:

@page
@model Valuable.Pages.ExceptionsModel
@{
    string message = "";
    double result = 0.00;
    string oper = "";
    double number1 = 0.00, number2 = 0.00;

    if (Request.HasFormContentType)
    {
        try
        {
            number1 = double.Parse(Request.Form["txtNumber1"]);
            number2 = double.Parse(Request.Form["txtNumber2"]);
            oper = Request.Form["txtNumber2"];

            if( (oper != "+") && (oper != "-") && (oper != "*") && (oper != "/") )
            {
                throw new Exception(oper);
            }

            switch (oper)
            {
                case "+":
                    result = number1 + number2;
                    break;
                case "-":
                    result = number1 - number2;
                    break;
                case "*":
                    result = number1 * number2;
                    break;
                case "/":
                    result = number1 / number2;
                    break;
                default:
                    message = "Bad Operation";
                    break;
            }

        }
        catch (FormatException)
        {
            message = "You typed an invalid number. Please correct it";
        }
        catch (Exception exc)
        {
            message = "Operation Error: " + exc.Message + " is not a valid operator";
        }
    }
}

<h3>Elementary Algebra</h3>

@using (Html.BeginForm())
{
    <table>
        <tr>
            <td>Number 1:</td>
            <td>@Html.TextBox("txtNumber1", @number1)</td>
        </tr>
        <tr>
            <td>Operator:</td>
            <td>@Html.TextBox("txtOperator", @oper)</td>
        </tr>
        <tr>
            <td>Number 2:</td>
            <td>@Html.TextBox("txtNumber2", @number1)</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnCalculate" value="Calculate" /></td>
        </tr>
        <tr>
            <td>Result:</td>
            <td>@Html.TextBox("txtResult", @result)</td>
        </tr>
    </table>

    <p>@message</p>
}

Obviously various bad things could happen when a form is used. Imagine that the user wants to perform a division. You need to tell the webpage what to do if the user enters the denominator as 0 (or 0.00). If this happens, one of the options you should consider is to display a message and get out. Fortunately, the .NET library provides the DivideByZeroException class to which we were introduced in the previous lesson to deal with an exception caused by division by zero. As done with the message passed to the Exception class, you can compose your own message and pass it to the DivideByZeroException(string message) constructor.

Exception Filters

Sometimes, in your application, you will have different sections that may throw the same type of exception. The problem is that these sections may present the same error message. For example, if you have more than two sections that expect numeric values, if a valid value is not provided, each of the sections would throw a FormatException exception. The problem is that when one of those sections throws the exception, you may need a way to either know what section threw the exception or what exception was thrown.

Filtering an exception consists of specifying a criterion by which a particular exception, among others, would be selected. The C# language provides a mechanism that allows you to get more details about an exception. To start, you must use a technique that would be applied to each particular error. One way to do this is to use the throw keyword to create a custom message when an exception is thrown. To help you select an exception, the C# language provides the when keyword. The formula to use it is:

try
{
	. . .
}
catch(exception-parameter) when (condition)
{
	. . .
}

In the catch clause, pass an exception-parameter as we have done so far. This is followed by the when keyword that is used as in an if() conditional statement. In its parentheses, provide a logical expression that can evaluate to true or false. If that expression is true, the body of the catch clause would execute.

Nesting an Exception

You can create an exception inside of another. This is referred to as nesting an exception. This is done by applying the same techniques we used to nest conditional statements. This means that you can write an exception that depends on, and is subject to, another 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 clause(s). To effectively handle the exception(s), make sure you include an appropriate throw in the try block. Here is an example:

@page
@model Valuable.Pages.ExceptionsModel
@{
    string message = "";
    double result = 0.00;
    string oper = "";
    double number1 = 0.00, number2 = 0.00;

    if (Request.HasFormContentType)
    {
        try
        {
            number1 = double.Parse(Request.Form["txtNumber1"]);
            number2 = double.Parse(Request.Form["txtNumber2"]);
            oper = Request.Form["txtOperator"];

            if( (oper != "+") && (oper != "-") && (oper != "*") && (oper != "/") )
            {
                throw new Exception(oper);
            }

            switch (oper)
            {
                case "+":
                    result = number1 + number2;
                    break;
                case "-":
                    result = number1 - number2;
                    break;
                case "*":
                    result = number1 * number2;
                    break;
                case "/":
                    try
                    {
                        if (number2 == 0)
                        {
                            throw new DivideByZeroException("Division by zero is not allowed");
                        }

                        result = number1 / number2;
                    }
                    catch (DivideByZeroException ex)
                    {
                        message = ex.Message;
                    }
                    break;
                default:
                    message = "Bad Operation";
                    break;
            }
        }
        catch (FormatException)
        {
            message = "You type an invalid number. Please correct it";
        }
        catch (Exception ex)
        {
            message = "Operation Error: " + ex.Message + " is not a valid operator";
        }
    }
}

<h3>Elementary Algebra</h3>

@using (Html.BeginForm())
{
    <table>
        <tr>
            <td>Number 1:</td>
            <td>@Html.TextBox("txtNumber1", @number1)</td>
        </tr>
        <tr>
            <td>Operator:</td>
            <td>@Html.TextBox("txtOperator", @oper)</td>
        </tr>
        <tr>
            <td>Number 2:</td>
            <td>@Html.TextBox("txtNumber2", @number1)</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnCalculate" value="Calculate" /></td>
        </tr>
        <tr>
            <td>Result:</td>
            <td>@Html.TextBox("txtResult", @result)</td>
        </tr>
    </table>

    <p>@message</p>
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2022, FunctionX Friday 04 February 2022 Next