Bird
0
0

What will be the output of the following C# code?

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Exception Handling
What will be the output of the following C# code?
try {
    int[] arr = new int[2];
    Console.WriteLine(arr[5]);
} catch (IndexOutOfRangeException e) {
    Console.WriteLine("Index error caught");
} catch (Exception e) {
    Console.WriteLine("General error caught");
}
AGeneral error caught
BCompilation error
CNo output, program crashes
DIndex error caught
Step-by-Step Solution
Solution:
  1. Step 1: Identify the exception thrown

    Accessing index 5 in an array of size 2 throws IndexOutOfRangeException.
  2. Step 2: Check which catch block handles it

    The first catch block specifically catches IndexOutOfRangeException, so it runs and prints "Index error caught".
  3. Final Answer:

    Index error caught -> Option D
  4. Quick Check:

    Specific catch runs before general [OK]
Quick Trick: Specific exceptions catch before general ones [OK]
Common Mistakes:
MISTAKES
  • Thinking general Exception catch runs first
  • Assuming program crashes without catch
  • Confusing IndexOutOfRangeException with ArgumentException

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes