Fractions
Summary
In this exercise you will practice handling mathematical fractions and the dangers that come with them, along with more Classes and Objects. You will make use of the 'try'/'catch' statements to prevent your program from experiencing sudden death.
Task
- Create a new C# Console project in Visual Studio.
- Right click the Project name found in the Solution Explorer on the right hand side of Visual Studio, select 'Add', select 'New item...' and finally select 'Class' from the list. Give it the name 'FractionClass.cs' and click 'Add'.
- Add code to your 'FractionClass' Class to work with a Numerator and Divisor, along with a parameterised Constructor method that allows the creation of Objects by using the syntax:
FractionClass f = new FractionClass (34, 3)
Hint: Make use of the integer data type.
- Further enhance the 'FractionClass' Class with a read-only property called 'Result' that, by default, calculates and returns the result of the division operation:
Numerator / Divisor
- Add code to your 'Main()' Method that will create a new 'FractionClass' object and set the Divisor property to 0. Print the 'Result' property to che Console screen. Test out your code. This should crash your program with a Divide by Zero Exception.
- Enhance your 'Main()' Method with a 'try'/'catch' to stop the program from carshing, but instead print out the Exception message.
- Enhance the 'set' part of the 'Divisor' property to throw a new 'ArgumentException' Exception.
- Further enhance your 'Main()' Method to prevent the program from crashing from your latest modification (handle the 'ArgumentException' Exception). Test out your program to prove the Exception is thrown and handled correctly.
Questions
- What would be the easiest way of making the 'FractionClass' constructor also perform this (Task 8.) check?
Hint: It's not a simple copy & paste solution.
- How would you change the 'FractionClass' to work with Floats instead of Integers? Note the different behaviour.