Exception propagation with methods : Exception : Language Basics C# Examples


C# Examples » Language Basics » Exception »

 

Exception propagation with methods









    
using  System;

class  MainClass
{
    public  static  void  Main()
    {
        Console.WriteLine("Calling  AccessInvalidArrayElement()");
        AccessInvalidArrayElement();

        try
        {
            Console.WriteLine("Calling  DivideByZero()");
            DivideByZero();

        }  catch  (DivideByZeroException  e)  {
            Console.WriteLine("Handling  an  IndexOutOfRangeException");
            Console.WriteLine("Message  =  "  +  e.Message);
            Console.WriteLine("StackTrace  =  "  +  e.StackTrace);
        }
    }

    public  static  void  AccessInvalidArrayElement()
    {
        int[]  myArray  =  new  int[2];
        try
        {
            Console.WriteLine("Attempting  to  access  an  invalid  array  element");
            myArray[20]  =  1;
        }
        catch  (IndexOutOfRangeException  e)
        {
            Console.WriteLine("Handling  an  IndexOutOfRangeException");
            Console.WriteLine("Message  =  "  +  e.Message);
            Console.WriteLine("StackTrace  =  "  +  e.StackTrace);
        }
    }

    public  static  void  DivideByZero()
    {
        int  zero  =  0;
        Console.WriteLine("Attempting  division  by  zero");
        int  myInt  =  1  /  zero;
    }

}
    
   
  
   



Output

Calling AccessInvalidArrayElement()
Attempting to access an invalid array element
Handling an IndexOutOfRangeException
Message = Index was outside the bounds of the array.
StackTrace =    at MainClass.AccessInvalidArrayElement()
Calling DivideByZero()
Attempting division by zero
Handling an IndexOutOfRangeException
Message = Attempted to divide by zero.
StackTrace =    at MainClass.Main()


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Language Basics
» Exception