Bird
0
0

The following code throws an exception. What is the main cause?

medium📝 Debug Q14 of 15
C Sharp (C#) - Strings and StringBuilder
The following code throws an exception. What is the main cause?
string s = "example";
int pos = s.IndexOf("z");
string part = s.Substring(pos, 3);
Console.WriteLine(part);
ASubstring called with negative start index
BIndexOf throws exception if not found
CLength parameter is too large
DConsole.WriteLine cannot print substrings
Step-by-Step Solution
Solution:
  1. Step 1: Check IndexOf result for "z"

    "z" is not in "example", so IndexOf returns -1.
  2. Step 2: Substring called with start index -1 causes exception

    Substring cannot start at negative index, so it throws ArgumentOutOfRangeException.
  3. Final Answer:

    Substring called with negative start index -> Option A
  4. Quick Check:

    Negative index in Substring causes error [OK]
Quick Trick: Check if IndexOf is -1 before using Substring [OK]
Common Mistakes:
MISTAKES
  • Assuming IndexOf throws exception when not found
  • Ignoring negative index causes Substring error
  • Blaming Console.WriteLine for error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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