Skip to content

8.2 Exceptions (throw and catch)

  1. If needed, start from the project up to chapter 7. This contains the classes as you left them at the end of chapter 7.
  2. Change the code of the Radius setter in the Circle class 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;
        }
    }
    

    ArgumentException is an exception that indicates invalid arguments. The setter checks whether a valid radius is provided and throws an exception if not.

  3. Modify the all-args constructor in the Circle class 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.

  4. Add the following code to the Main method 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.");
    }
    
  5. 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.
    
  6. Apply the same validation to the Length and Width setters in the Rectangle class, and update the all-args constructor accordingly.

  7. Add similar code in your Main method to test rectangle input with length and width validation.