Create Custom Exception - CSharp Custom Type

CSharp examples for Custom Type:Exception

Description

Create Custom Exception

Demo Code

using System;//  w w w  .ja  v  a 2  s.c o  m
public class LogarithmicException : System.ApplicationException
{
   private uint errorNumber;
   public LogarithmicException() : base("Logarithmic exception")
   {
      errorNumber = 1000;
   }
   public LogarithmicException(string message, uint initErrorNumber) : base(message)
   {
      errorNumber = initErrorNumber;
   }
   public uint ErrorNumber
   {
      get
      {
         return errorNumber;
      }
   }
}
class MyMath
{
   public static double CalculateLog(double num)
   {
      try
      {
         if(num < 0.0)
         {
            throw new LogarithmicException("Logarithm of a negative number cannot be calculated", 1001);
         }
         if(num == 0.0)
         {
            throw new LogarithmicException("Logarithm of zero is -infinity", 1002);
         }
         return Math.Log(num);
      }
      catch(LogarithmicException exObj)
      {
         Console.WriteLine("Message: " + exObj.Message);
         Console.WriteLine("Error number: " + exObj.ErrorNumber);
         throw new ArithmeticException("Invalid number for Logarithm calculation");
      }
   }
}
class Tester
{
   public static void Main()
   {
      try
      {
         double number;
         double result;
         Console.Write("Calculate Log for the following number: ");
         number = Convert.ToDouble(Console.ReadLine());
         result = MyMath.CalculateLog(number);
         Console.WriteLine("The result is: {0}", result);
      }
      catch(ArithmeticException exObj)
      {
         Console.WriteLine(exObj.Message);
      }
   }
}

Result


Related Tutorials