Wednesday, November 21, 2012

More Validation and Error Trapping

Here is an example of a program that validates the user choices with TryParse instead of Parse. It also shows the use of try catch blocks and how to throw an exception.

The program consists of three classes. The Program class which contains the Main() method, and nothing else. The Display class which calls the SimpleMath class which does simple integer addition, subtraction, multiplication and division

We will start with the validation of the inputs in the Display class.

First we set up a menu. (The menu, by the way, uses a switch structure which tests each "case" of the variable "choice." If choice is equal to 1 it call the the GetNumbers() method and the GetAddition() method. The break keeps it from sliding down to the next case.

Here is the basic menu:

Notice the menu loops until the user chooses 5 to exit. Also note the validation of the user choice. It uses a TryParse method to test the value. The TryParse value returns a boolean--true of false. If the input can be parsed as an integer it is passed out to the variable "choice". If not, it just returns false. In this instance I don't have to do anything else. It will keep looping until the user enters 5 to exit.

In the GetNumbers() method the user input is again tested with TryParse(). Here the input is inside a while loop that won't let the user out until they have entered a valid number.

After the numbers are validated they are assigned to properties in the SimpleMath class. Lets look at the SimpleMath class. I am going to focus on just the Division method. With integer division it is an error to divide by zero. I am going to put the division in a try catch block and look explicitly for the Division by zero error. I am going to throw the error back to the Display class which called the method. It is always best if your classes are as agnostic about the display modes as possible. The same class could be used in a console application such as this one, or with a web form or a window's form.

I did the same thing with the Remainder method

If you throw an error you must catch it somewhere. I put a try catch block around the code in the Display class that calls the divide method. It will catch and display the error.

Here is a picture of the console app running. I chose 4 for divide, and put 0 as the second integer. The error message, thrown from the SimpleMath class and caught by the Display class is shown

So here is all the code in a form you can cut and paste


SimpleMath

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tryCatchExamples
{
    class SimpleMath
    {
        /// 
        /// This class just does simple arithmetic.
        /// Its main point is in the Divide method.
        /// There it has a try catch that catches the 
        /// DivideByZeroException. It throws this to the
        /// calling class which is Display
        /// 
        /// 
        // private fields 
        private int number1;
        private int number2;

        //default constructor
        public SimpleMath()
        {
            number1 = 0;
            number2 = 0;
        }

        //overloaded constructor
        public SimpleMath(int num1, int num2)
        {
            number1 = num1;
            number2 = num2;
        }

        //public properties
        public int Number1
        {
            set { number1 = value; }
            get { return number1; }
        }

        public int Number2
        {
            set { number2 = value; }
            get { return number2; }
        }

        //public methods

        public int Add()
        {
            return number1 + number2;
        }

        public int Subtract()
        {
            return number1 - number2;
        }

        public int Multiply()
        {
            return number1 * number2;
        }


        public int Divide()
        {
            int quotient=0;
            //here we try the division if number2
            //is 0 it will throw an error
            //backt to the calling class
            try //try the following code
            {
                quotient = number1 / number2;
            }
            catch (DivideByZeroException) //catch the Divide by zero error
            {
                throw new DivideByZeroException();
            }

            return quotient;
        }

        public int Remainder()
        {
            int remain = 0;
            {
                try //try the following code
                {
                    remain = number1 % number2;
                }
                catch (DivideByZeroException) //catch the Divide by zero error
                {
                    throw new DivideByZeroException();
                }

                return remain;
            }
        }
    }
}


Display

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tryCatchExamples
{
    class Display
    {
        private SimpleMath simpleMath;
        private int num1;
        private int num2;

        public Display()
        {
            simpleMath = new SimpleMath();
            menu();
        }

        private void menu()
        {
            int choice = 1;
            while (choice !=5)
            {
                Console.Clear();
                Console.WriteLine("Choose which operation you wish to do:"
                    +"\n1: Add" 
                    +"\n2: Subtract"
                    +"\n3: Multiply"
                    +"\n4: divide"
                    +"\n5: Exit");

                bool menuitem= int.TryParse(Console.ReadLine(), out choice);
                switch (choice)
                {
                    case 1:
                        GetNumbers();
                        GetAdd();
                        break;
                    case 2:
                        GetNumbers();
                        GetSubtract();
                        break;
                    case 3:
                        GetNumbers();
                        GetMultiply();
                        break;
                    case 4:
                        GetNumbers();
                        GetDivide();
                        break;
                    default:
                        break;
                }
            }
        }

        private void GetNumbers()
        {
            bool goodNumber = false;
            bool goodNumber2 = false;
            while (!goodNumber)
            {
                Console.WriteLine("Enter the first integer");
                goodNumber = int.TryParse(Console.ReadLine(), out num1);

                if (!goodNumber)
                {
                    Console.WriteLine("enter a valid integer");
                }

            }

            while (!goodNumber2)
            {
                Console.WriteLine("Enter the Second integer");
                goodNumber2 = int.TryParse(Console.ReadLine(), out num2);

                if (!goodNumber2)
                {
                    Console.WriteLine("enter a valid integer");
                }

            }
            simpleMath.Number1 = num1;
            simpleMath.Number2 = num2;
        }

            private void GetAdd()
            {
                Console.WriteLine("The sum is {0}", simpleMath.Add() );
                PauseIt();
            }

            private void GetSubtract()
            {
                Console.WriteLine("The Difference is {0}", simpleMath.Subtract());
                PauseIt();
            }

            private void GetMultiply()
            {
                Console.WriteLine("The product is {0}", simpleMath.Multiply());
                PauseIt();
            }

            private void GetDivide()
            {
                int quotient;
                int remainder;
                try
                {
                    quotient = simpleMath.Divide();
                    remainder = simpleMath.Remainder();
                    Console.WriteLine("the quotient is {0}", quotient);
                    Console.WriteLine("The remainder is {0}", remainder);
                    PauseIt();
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    PauseIt();
                }
            }

            private void PauseIt()
            {
                Console.WriteLine("Press any key to continue");
                Console.ReadKey();
            }

    }
}


Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tryCatchExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            Display d = new Display();
        }
    }
}

No comments:

Post a Comment