Bird
Raised Fist0

What will be the output of this C# code?

medium📝 Predict Output Q5 of Q15
C Sharp (C#) - Exception Handling

What will be the output of this C# code?

try {
  string s = null;
  Console.WriteLine(s.Length);
} catch (ArgumentNullException) {
  Console.WriteLine("Argument null error");
} catch (NullReferenceException) {
  Console.WriteLine("Null reference error");
} catch (Exception) {
  Console.WriteLine("General error");
}
ANo output, program crashes
BArgument null error
CGeneral error
DNull reference error
Step-by-Step Solution
Solution:
  1. Step 1: Identify the exception thrown

    Accessing Length on a null string throws NullReferenceException.
  2. Step 2: Match exception to catch blocks

    The NullReferenceException catch block matches and prints "Null reference error".
  3. Final Answer:

    Null reference error -> Option D
  4. Quick Check:

    NullReferenceException triggers its catch block [OK]
Quick Trick: NullReferenceException catch runs on null object access [OK]
Common Mistakes:
MISTAKES
  • Confusing ArgumentNullException with NullReferenceException
  • Expecting general catch to run
  • Assuming program crashes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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