Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Jul 2, 2022, 2:07 PM EDT
Joginder BangerRank #360 · 7K reputationPosted Jul 2, 2022, 10:51 AM EDT
Jaydeep PatilRank #205 · 11.7K reputationPosted Jul 3, 2022, 1:50 AM EDT
Take care of your index and size of the collection while iterating and also handle exception properly.
Salman BegRank #284 · 8.8K reputationPosted Jul 5, 2022, 2:27 PM EDT
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Jul 5, 2022, 4:13 PM EDT
PhamNgoc Khiem39 reputationPosted Jul 13, 2022, 3:28 AM EDT
This is the error was occurred by your index query exceed the total index array. You can prevent it by this way
Pushpendra ShuklaRank #552 · 4.4K reputationPosted Jul 13, 2022, 8:48 AM EDT
What is the Index Out of Range Exception?
If we initialize the array size and print the value greater than the array size. For example, we initialize the array size 5 and we print the values of 6 index that time array shows Index Out of Range Exception.
This is the code for preventing Index Out of Range Exceptions.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Indexoutofrangeexception { internal class Program { static void Main(string[] args) { int[] arr = { 1, 2, 3, 4, 5}; for (int i = 0; i <= arr.Length; i++) { Console.WriteLine(arr[i]); } Console.ReadLine(); } } }Output
How to handle this exception
This is the solution to handle the Index Out of Range Exception.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Indexoutofrangeexception { internal class Program { static void Main(string[] args) { int[] arr = { 1, 2, 3, 4, 5}; try { for (int i = 0; i <= arr.Length; i++) { Console.WriteLine(arr[i]); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } }output