Users Online

· Guests Online: 98

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C# Program to Demonstrate IndexOutOfRange Exception

C# Program to Demonstrate IndexOutOfRange Exception

 

 

This is a C# Program to demonstrate IndexOutOfRange exception.

Problem Description

This C# Program Demonstrates IndexOutOfRange Exception.

Problem Solution

Here if the array has the index value out of the range that is specified then this exception is thrown.

Program/Source Code

Here is source code of the C# Program to Demonstrate IndexOutOfRange Exception. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Demonstrate IndexOutOfRange Exception
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace differnce
{
    class arrayoutofindex
    {
        public void calculatedifference()
        {
            int difference=0;
            int [] number= new int[5] {1,2,3,4,5};
            try
            {
                for (int init =1; init <=5; init++)
                {
                    difference= difference -  number[init];
                }
                Console.WriteLine("The difference of the array is:" + difference);
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
    class classmain
    {
        static void Main(string [] args)
    {
        arrayoutofindex obj = new arrayoutofindex();
        obj.calculatedifference();
        Console.ReadLine();
    }
}
}
Program Explanation

This C# program is used to demonstrate IndexOutOfRange exception. Create an object ‘ob’ variable to arrayoutofindex class, then using object variable perform the calculateddifference() procedure.

 

 

In calculatedifference() procedure assign an value to the number[] array variable. In try statement for loop is used to compute the difference between the value of ‘variable’ by the value of ‘number[]’ array variable.

If the array has the index value out of the range that is specified then the exception is thrown. Using try and catch, an error message is displayed when the error occurs.

Runtime Test Cases
 
Index was outside the bounds of the array

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.00 seconds
10,832,626 unique visits