Create custom NegativeNumberException to represent exceptions caused by illegal operations performed on negative numbers. - CSharp Custom Type

CSharp examples for Custom Type:Exception

Description

Create custom NegativeNumberException to represent exceptions caused by illegal operations performed on negative numbers.

Demo Code




using System;// w w w . j a va 2s  . co m

class MainClass
{
   static void Main(string[] args)
   {
      var continueLoop = true;

      do
      {
         try
         {
            Console.Write("Enter a value to calculate the square root of: ");
            double inputValue = double.Parse(Console.ReadLine());
            double result = SquareRoot(inputValue);

            Console.WriteLine($"The square root of {inputValue} is {result:F6}\n");
            continueLoop = false;
         }
         catch (FormatException formatException)
         {
            Console.WriteLine("\n" + formatException.Message);
            Console.WriteLine("Please enter a double value.\n");
         }
         catch (NegativeNumberException negativeNumberException)
         {
            Console.WriteLine("\n" + negativeNumberException.Message);
            Console.WriteLine("Please enter a non-negative value.\n");
         }
      } while (continueLoop);
   }

   public static double SquareRoot(double value)
   {
      // if negative operand, throw NegativeNumberException
      if (value < 0)
      {
         throw new NegativeNumberException(
            "Square root of negative number not permitted");
      }
      else
      {
         return Math.Sqrt(value); // compute square root
      }
   }
}
public class NegativeNumberException : Exception
{
   // default constructor
   public NegativeNumberException(): base("Illegal operation for a negative number")
   {
      // empty body
   }

   // constructor for customizing error message
   public NegativeNumberException(string messageValue)
      : base(messageValue)
   {
      // empty body
   }

   // constructor for customizing the exception's error
   // message and specifying the InnerException object
   public NegativeNumberException(string messageValue, Exception inner)
      : base(messageValue, inner)
   {
      // empty body
   }
}

Result


Related Tutorials