C#.NET — What will this program print when it tries to write a[6] (array size 5)? using System; namespace CuriousTabConsoleApplication { class MyProgram { static void Main(string[] args) { int index = 6; int val = 44; int[] a = new int[5]; try { a[index] = val; } catch (IndexOutOfRangeException e) { Console.Write("Index out of bounds "); } Console.Write("Remaining program"); } } }

Difficulty: Easy

Correct Answer: It will output: Index out of bounds Remaining program

Explanation:


Introduction / Context:
This problem tests your knowledge of array bounds and specific exception handling with IndexOutOfRangeException in C#. It also checks whether you understand that execution continues after a handled exception.



Given Data / Assumptions:

  • Array declared as new int[5] has valid indices 0..4.
  • Code attempts to write to a[6].
  • There is a catch (IndexOutOfRangeException) and a print after the try/catch.


Concept / Approach:
Attempting to access index 6 on a 5-element array throws an IndexOutOfRangeException. The catch block prints a message and execution then proceeds to the statement after the catch, printing the final text. Thus, two messages appear, in order.



Step-by-Step Solution:

Array length = 5 → allowed indices 0..4.Access a[6] → throws IndexOutOfRangeException.Catch executes: prints "Index out of bounds ".After catch, prints "Remaining program".


Verification / Alternative check:
Changing index to a legal value (such as 4) would print only "Remaining program" because the catch would not run.



Why Other Options Are Wrong:

  • Assignment succeeds: impossible because index 6 is invalid.
  • Only one of the messages: ignores continued execution after a handled exception.
  • No output: the program prints in both paths.


Common Pitfalls:
Confusing length with highest index (highest index is Length - 1). Also, forgetting that a handled exception allows the program to continue.



Final Answer:
It will output: Index out of bounds Remaining program

More Questions from Exception Handling

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion