Throw exception out of method - CSharp Custom Type

CSharp examples for Custom Type:Exception

Description

Throw exception out of method

Demo Code

using System;/*from  www. j a  va  2 s .  com*/
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("Inside Main's catch block");
         Console.WriteLine("Message: " + exObj.Message);
         Console.WriteLine("Help Link: " + exObj.HelpLink);
         Console.WriteLine("Method call trace: " + exObj.StackTrace);
      }
   }
}
class MyMath
{
   public static double CalculateLog(double num)
   {
      try
      {
         if(num < 0.0)
         {
            throw new ArithmeticException("Logarithm of a negative number cannot be calculated");
         }
         if(num == 0.0)
         {
            ArithmeticException arithEx = new ArithmeticException("Logarithm of zero is -infinity");
            arithEx.HelpLink = "http://www.themathwizards@#$.com";
            throw arithEx;
         }
         return Math.Log(num);
      }
      catch(ArithmeticException exObj)
      {
         Console.WriteLine("Inside CalculateLog's catch block");
         throw exObj;
      }
   }
}

Result


Related Tutorials