Home

Introduction to

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 os we can assist the user of our application when an error occurs in our application.

Practical LearningPractical Learning: Introducing Exception Handling

  1. Start Microsoft Visual Studio. On the Visual Studio 2019 dialog box, click Create a New Project (if Microsoft Visual Studio was already opened, on the main menu, click File -> New -> Project...)
  2. In the Create New a New Project dialog box, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the project Name to PledgeDistribution1
  5. Create Create
  6. Design the form as follows:

    Introducing Events

    Control (Name) Text TextAlign
    Label   Organization for Fundraising Events  
    Label   __________________________________  
    Label   Two-Way Campaign Distribution  
    Label   Amount to Allocate:  
    TextBox txtAllocation    
    Label   In the Ratio:  
    TextBox txtPortion1   Center
    Label   :  
    TextBox txtPortion2   Center
    Button btnCalculate Calculate  
    Label   __________________________________  
    Label   Part 1 Receives:  
    TextBox txtPart1    
    Label   Part 2 Receives:  
    TextBox txtPart2    
  7. Double-click the Calculate button
  8. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PledgeDistribution1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            int DistributeFirstPart(int amount, int portion1, int portion2)
            {
                int totalRatios = portion1 + portion2;
                int eachPart = amount / totalRatios;
                int result = eachPart * portion1;
    
                return result;
            }
    
            int Subtract(int first, int second)
            {
                return first - second;
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                int part1;
                int part2;
                int ratio1;
                int ratio2;
                int amtPledged;
    
                amtPledged = int.Parse(txtAllocation.Text);
                ratio1 = int.Parse(txtPortion1.Text);
                ratio2 = int.Parse(txtPortion2.Text);
    
                part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
                part2 = Subtract(amtPledged, part1);
            }
        }
    }
  9. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introducing Exception Handling

  10. In the top 3 text boxes, enter the following values:
    Amount to Allocate: 6450
    In the Ratio: 1
                 : 1
    
    

    Introducing Exception Handling

  11. Click the Calculate button

    Introducing Exception Handling

  12. Change the ratio to 3:2 and click the Calculate button:

    Creating a Partial Class

  13. Close the form and 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(txtNumber.Text);
        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
    }

Practical LearningPractical Learning: Introducing Exceptional Behaviors

  1. To introduce exceptions, change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PledgeDistribution1
    {
        public partial class Form1 : Form
        {
            . . .
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                int part1;
                int part2;
                int ratio1;
                int ratio2;
                int amtPledged;
    
                try
                {
                    amtPledged = int.Parse(txtAllocation.Text);
                    ratio1 = int.Parse(txtPortion1.Text);
                    ratio2 = int.Parse(txtPortion2.Text);
    
                    part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
                    part2 = Subtract(amtPledged, part1);
    
                    txtPart1.Text = part1.ToString();
                    txtPart2.Text = part2.ToString();
                }
                catch
                {
    
                }
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. In the top text box, type 1250000
  4. Click the Calculate button:

    Introducing Exceptional Behaviors

  5. Close the form and return to your programming environment

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:

double number, result;

try
{
    number = double.Parse(txtNumber.Text);
    result = number * 2.00;
}
catch
{
    MessageBox.Show("The value you entered is not a valid number.")
}

Practical LearningPractical Learning: Displaying Custom Messages

  1. To display custom messages to the visitor, change the code of the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PledgeDistribution1
    {
        public partial class Form1 : Form
        {
            public Form1() => InitializeComponent();
    
            public int DistributeFirstPart(int amount, int portion1, int portion2)
            {
                int totalRatios = portion1 + portion2;
                int eachPart = amount / totalRatios;
                int result = eachPart * portion1;
    
                return result;
            }
    
            public int Subtract(int first, int second) => first - second;
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                int part1;
                int part2;
                int ratio1;
                int ratio2;
                int amtPledged;
    
                try
                {
                    amtPledged = int.Parse(txtAllocation.Text);
                    ratio1 = int.Parse(txtPortion1.Text);
                    ratio2 = int.Parse(txtPortion2.Text);
    
                    part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
                    part2 = Subtract(amtPledged, part1);
    
                    txtPart1.Text = part1.ToString();
                    txtPart2.Text = part2.ToString();
                }
                catch
                {
                    MessageBox.Show("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.",
                                    "Organization for Fundraising Events");
                }
            }
        }
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. Click the Calculate button

    Introducing Exception Handling

  4. Close the form and return to your programming environment

Introduction to Exceptions in the .NET Framework

The Exception Class

To support exception handling, the .NET Framework 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.

Practical LearningPractical Learning: Introducing the Exception Class/p>

  1. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PledgeDistribution1
    {
        public partial class Form1 : Form
        {
            public Form1() => InitializeComponent();
    
            public int DistributeFirstPart(int amount, int portion1, int portion2)
            {
                int totalRatios = portion1 + portion2;
                int eachPart = amount / totalRatios;
                int result = eachPart * portion1;
    
                return result;
            }
    
            public int Subtract(int first, int second) => first - second;
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                int part1, part2;
                int ratio1, ratio2, amtPledged;
    
                try
                {
                    amtPledged = int.Parse(txtAllocation.Text);
                    ratio1 = int.Parse(txtPortion1.Text);
                    ratio2 = int.Parse(txtPortion2.Text);
    
                    part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
                    part2 = Subtract(amtPledged, part1);
    
                    txtPart1.Text = part1.ToString();
                    txtPart2.Text = part2.ToString();
                }
                catch(Exception exc)
                {
                    MessageBox.Show(exc.Message,
                                    "Organization for Fundraising Events");
                }
            }
        }
    } 
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. Click the Calculate button

    Introducing Exception Handling

  4. Close the form and return to your programming environment

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(txtNumber.Text);
    result = number * 2.00;
}
catch(Exception exc)
{
    MessageBox.Show("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 btnCalculate_Click(object sender, EventArgs e)
{
    try
    {
    }
    catch(Exception _)
    {
        MessageBox.Show(" 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.",
                        "Organization for Fundraising Events");
    }
}

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

void btnCalculate_Click(object sender, EventArgs e)
{
    try
    {
    }
    catch(Exception exc)
    {
        MessageBox.Show(exc.Message,
                        "Organization for Fundraising Events");
    }
}

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

void btnCalculate_Click(object sender, EventArgs e)
{
    try
    {
    }
    catch(Exception exc)
    {
        MessageBox.Show(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.",
                        "Organization for Fundraising Events");
    }
}

Custom Message

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

void btnCalculate_Click(object sender, EventArgs e)
{
    try
    {
    }
    catch(Exception)
    {
        MessageBox.Show(" 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.",
                        "Organization for Fundraising Events");
    }
}

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 Framework 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 Framework provides various classes to handle almost any type of exception. When your application produces an error, the compiler will display a message box to notify the user. Here is an example of such a message box:

The Format Exception

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 Framework. 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 {
    number = double.Parse(Request["txtNumber"]);
    result = number * 2.00;
}
catch(FormatException exc)
{
    MessageBox.Show("The value you entered is not a valid number.");
}

Practical LearningPractical Learning: Using the FormatException Class

  1. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PledgeDistribution1
    {
        public partial class Form1 : Form
        {
            public Form1() => InitializeComponent();
    
            public int DistributeFirstPart(int amount, int portion1, int portion2)
            {
                int totalRatios = portion1 + portion2;
                int eachPart = amount / totalRatios;
                int result = eachPart * portion1;
    
                return result;
            }
    
            public int Subtract(int first, int second) => first - second;
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                int part1, part2;
                int ratio1, ratio2, amtPledged;
    
                try
                {
                    amtPledged = int.Parse(txtAllocation.Text);
                    ratio1 = int.Parse(txtPortion1.Text);
                    ratio2 = int.Parse(txtPortion2.Text);
    
                    part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
                    part2 = Subtract(amtPledged, part1);
    
                    txtPart1.Text = part1.ToString();
                    txtPart2.Text = part2.ToString();
                }
                catch(FormatException)
                {
                    MessageBox.Show("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.",
                                    "Organization for Fundraising Events");
                }
            }
        }
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. Close the form and 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.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2021, FunctionX Next