Bird
Raised Fist0

What will be the output of this code snippet?

medium📝 Predict Output Q4 of Q15
C Sharp (C#) - Exception Handling
What will be the output of this code snippet?
try {
  int[] arr = new int[2];
  Console.WriteLine(arr[3]);
} catch (IndexOutOfRangeException) {
  Console.WriteLine("Index error");
} catch (Exception) {
  Console.WriteLine("General error");
}
ANo output
BGeneral error
CRuntime crash
DIndex error
Step-by-Step Solution
Solution:
  1. Step 1: Identify exception thrown

    Accessing arr[3] when array size is 2 throws IndexOutOfRangeException.
  2. Step 2: Match catch block

    The first catch block matches IndexOutOfRangeException and prints "Index error".
  3. Final Answer:

    Index error -> Option D
  4. Quick Check:

    Specific catch handles IndexOutOfRangeException [OK]
Quick Trick: Specific exceptions catch blocks run before general ones [OK]
Common Mistakes:
MISTAKES
  • Assuming general Exception catch runs first
  • Expecting runtime crash without catch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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