8.2 Exceptions (throw and catch)
- If needed, start from the project up to chapter 7. This contains the classes as you left them at the end of chapter 7.
-
Change the code of the
Radiussetter in theCircleclass as follows:1 2 3 4 5 6 7 8 9 10
public double Radius { get => _radius; set { if (value <= 0) throw new ArgumentException("The radius must be positive."); _radius = value; } }ArgumentExceptionis an exception that indicates invalid arguments. The setter checks whether a valid radius is provided and throws an exception if not. -
Modify the all-args constructor in the
Circleclass as follows:1 2 3 4 5
public Circle(double radius, Point center, string color) : base(color) { Radius = radius; // Use setter to validate _center = center; }The constructor now calls the setter, so an invalid radius cannot be set directly.
-
Add the following code to the
Mainmethod of your program:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Console.Write("Enter a radius: "); string? input = Console.ReadLine(); double radius = double.Parse(input ?? "0"); try { Circle enteredCircle = new Circle(radius); Console.WriteLine(enteredCircle); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } finally { Console.WriteLine("Your input has been processed."); } -
Run your program. Example with invalid input (-7):
1 2 3
Enter a radius: -7 The radius must be positive. Your input has been processed.Example with valid input (4):
1 2 3 4 5 6 7
Enter a radius: 4 Color: white Perimeter: 25.132741228718345 Area: 50.26548245743669 Radius: 4.0 Center: (0.00, 0.00) Your input has been processed. -
Apply the same validation to the
LengthandWidthsetters in theRectangleclass, and update the all-args constructor accordingly. -
Add similar code in your
Mainmethod to test rectangle input with length and width validation.