Watts Calculator, struggling to get my exception handling working.

LostNativ

Member
Joined
May 7, 2021
Messages
5
Programming Experience
Beginner
I want to be able to catch errors and ask the user for valid inputs.
C#:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace S1P1

{

    class Program

    {

        public delegate float WattsLawDelegate(float num1, float num2);

        static void Main(string[] args)

        {

            // Name              : void Main(string[] args)

            // Purpose           : Main entry point to the program

            // Re-use            : DisplayMenu(); GetMenuOption(); GetValue(); CalcVoltage(); CalcResistance(); CalCurrent()

            // Method Parameters : string[] args

            //                      - console/command line arguments

            // Output Type       : None



            string endCal = "";

            float userInput1 = 0;

            float userInput2 = 0;

            float result = 0;

            string messageCal = "";

            bool input = false;



            WattsLawDelegate wattsLaw = null;

            DisplayMenu();

            endCal =GetMenuOption();





            while (endCal != "X")

            {



                //switch

                switch (endCal)

                {

                    case "P":

                        userInput1 = GetValue("current");

                        userInput2 = GetValue("Voltage");

                        wattsLaw = new WattsLawDelegate(CalcPower);

                        messageCal = "The Power is: ";

                        input = true;

                       break;

                    case "V":

                        userInput1 = GetValue("power");

                        userInput2 = GetValue("current");

                        wattsLaw = new WattsLawDelegate(CalcVoltage);

                        messageCal = "The Volatage is: ";

                        input = true;

                        break;

                    case "I":

                        userInput1 = GetValue("voltage");

                        userInput2 = GetValue("resistance");

                        wattsLaw = new WattsLawDelegate(CalCurrent);

                        break;

                    case "X":

                        ;

                        break;

                    default:

                        Console.WriteLine("Invalid option, please try again");

                        break;

                } // end switch

                if (input)

                {

                    result = wattsLaw(userInput1, userInput2);

                    Console.WriteLine(messageCal + " " + result);

                    input = false;

                } // end if

                DisplayMenu();

                endCal = GetMenuOption();

            }

        }//main method



        public static void DisplayMenu()

        {

            //

            //Name                : void DisplayMenu()

            //Purpose            : Display the menu to the user on screen

            //Re-use            : None

            //Method Parameters    : None

            //Output Type       : None

            //



            Console.WriteLine("Watt's Law Calculator");

            Console.WriteLine("======================");

            Console.WriteLine(" P - Calculate the power\n I - Calculate the current\n V - Calculate the voltage\n X -Exit");



        }//end DisplayMenu



       public static string GetMenuOption()

        {

            //

            //Name                : string GetMenuOption()

            //Purpose            : Prompt the user for an option

            //Re-use            : None

            //Method Parameters    : None

            //Output Type       : string

            //                    - the option entered by the user

       

           

         

                Console.Write("Please enter V, P, I or X: ");

                return Console.ReadLine().ToUpper();

        }//end GetMenuOption



        public static float GetValue(string type)

        {

            //

            //Name                : int GetValue(string type)

            //Purpose            : Prompt the user for a value and parse it to float

            //Re-use            : None

            //Method Parameters    : string type

            //                    - the type of value to get: voltage, power or current

            //Output Type       : float

            //                    - the converted float entered by the user

            //

            try

            {

                Console.WriteLine("Please enter a " + type + " value: ");

             

            }

            catch(Exception ex)

            {

                Console.WriteLine("GetValue:" + ex.Message);

            }



            return float.Parse(Console.ReadLine());

        }



        public static float CalcPower(float current, float voltage)

        {

            //

            //Name                : int CalcResistance(float current, float voltage)

            //Purpose            : Calculate the Resistance using Watts Law

            //Re-use            : None

            //Method Parameters    : - float current

            //                      - voltage value in volts

            //                    - float voltage

            //                      - current value in amps

            //Output Type       : float

            //                    - the calculated power value



            float power = 0;



            try

            {

                power = current * voltage;

             



            }//end try



            catch(Exception ex)

            {

                Console.WriteLine("CalcPower:" + ex.Message);

            }

            return power;

        }//end CalcPower



        public static float CalcVoltage(float power, float current)

        {

            //

            //Name                : float CalcVoltage(float power, float power)

            //Purpose            : Calculate the Voltage using Watts Law

            //Re-use            : None

            //Method Parameters    : - float power

            //                    

            //                    - float power

            //                    

            //Output Type       : float

            //                    - the calculated Voltage value



            float voltage = 0;

         



            try

            {

                voltage = power / current;

             

            }

            catch (Exception ex)

            {

                Console.WriteLine("CalcVoltage:" + ex.Message);

            }

            return voltage;



        }//end CalcVoltage



        public static float CalCurrent(float power, float voltage)

        {



            //

            //Name                : int CalcCurrent(float power, float voltage)

            //Purpose            : Calculate the Current using Watts Law

            //Re-use            : None

            //Method Parameters    : - float power

            //                  

            //                    - float voltage

            //                    

            //Output Type       : float

            //                    - the calculated Current value



            float current = 0;



            try

            {

             current = power / voltage;

           



            }

            catch (Exception ex)

            {

                Console.WriteLine("CalCurrent:" + ex.Message);

            }

            return current;

        }//end CalCurrent



    }//end class



}//end namespace
 
In general, you don't want to use exception handling for errors which can be anticipated errors. Exceptions should be used for exceptional errors. Therefore use [il]TryParse()[/il] instead of using try-catch[/il] in your [icode]GetValue() method.
 
In general, you don't want to use exception handling for errors which can be anticipated errors. Exceptions should be used for exceptional errors. Therefore use [il]TryParse()[/il] instead of using try-catch[/il] in your [icode]GetValue() method.
Thank you, however, there is a possibility of a user dividing by 0 that a TryParse won't be able to handle. I just ran it as TryPase in a while loop. It worked for the character issue but not for divide by zero.
 
Why not check for a zero denominator first instead of blindly dividing?
 
Why not check for a zero denominator first instead of blindly dividing?
I would, but I am not quite sure how. Really new to this and I am doing this cause at the institution I am enrolled we aren't being challenged so I am taking it upon myself type thing. I am trying to learn the principles and best practise...
 
Instead of writing:
C#:
double ComputeVoltage(double power, double current)
{
    try
    {
        return power / current;
    }
    catch(DivideByZeroException ex)
    {
        Console.Error.WriteLine("Dividing power by zero valued current");
    }
    return Double.PositiveInifinity;
}

You could simply write:
C#:
double ComputeVoltage(double power, double current)
{
    if (current == 0)
    {
        Console.Error.WriteLine("Dividing power by zero valued current");        
        return Double.PositiveInifinity;
    }

    return power / current;
}
 
I just realized: it's quite possible that your school has deliberately given you this assignment so that you learn how to do exception handling. The assignment goes against industry best practices, but it is what it is. If the objective of the assignment is to learn exception handling, then the techniques above for avoiding the exceptions in the first place is moot.
 
And a quick comment about the use of DivideByZeroException in post #6. The exception will never be thrown. The exception is only for trying to divide by zero using integers and decimal types. The exception is not thrown for floating point numbers as per the documentation.

Dividing a floating-point value by zero doesn't throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic.
 
I really appreciate this. The school I go to is still teaching us variables and loops it's a bit of a shoddy school. I got this project from the students at another school I want to be good at this so I am joining forums and doing projects. In my neck of the world, you still need a formal qualification to get into software jobs but I want to step in with a decent knowledge and skill. That said. I am thankful for your time in helping me and being kind in your words.
 
Back
Top Bottom