Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The use of exceptions in C#

I try to use exception, so that when I input the value for width and length, the negative value is not executable. However, when I input negative value to the width and length, it is still executable. Can you tell me what may be the problem?
Here is my code:

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

namespace Rectangle_OOP
{
    public class Program
    {
        double width = 1;
        double length = 1;

        public Program()
        {
        }
        void Checksides(double width, double length)
        {
            if ((width<0) || (length< 0))
            {
                throw new Exception("Rectangle side is not valid");
            }
        }
        public static void Main(String[] args)
        {
            Program obj = new();
            obj.width = double.Parse(Console.ReadLine());
            obj.length = double.Parse(Console.ReadLine());
            double area = obj.width * obj.length;
            Console.WriteLine(area);
        }
    }
}

        

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The Checksides is never invoked

Simply change the Main method as follows

public static void Main(String[] args)
{
    Program obj = new();
    obj.width = double.Parse(Console.ReadLine());
    obj.length = double.Parse(Console.ReadLine());

    // Invoke the Checksides method 
    Checksides(obj.width, obj.length);

    double area = obj.width * obj.length;
    Console.WriteLine(area);
}

Fabio

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading