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 :
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