Bird
0
0

Which of the following code snippets correctly defines and uses this exception?

hard🚀 Application Q15 of 15
C Sharp (C#) - Exception Handling
You want to create a custom exception InvalidAgeException that should be thrown when a user's age is less than 0 or greater than 120. Which of the following code snippets correctly defines and uses this exception?
Aclass InvalidAgeException : Exception { public InvalidAgeException(string msg) : base(msg) {} }<br>void CheckAge(int age) { if(age < 0 || age > 120) throw new InvalidAgeException("Age is invalid"); }
Bclass InvalidAgeException { public InvalidAgeException(string msg) {} }<br>void CheckAge(int age) { if(age < 0 || age > 120) throw new InvalidAgeException("Age is invalid"); }
Cclass InvalidAgeException : Exception { public void InvalidAgeException(string msg) {} }<br>void CheckAge(int age) { if(age < 0 || age > 120) throw new InvalidAgeException("Age is invalid"); }
Dclass InvalidAgeException : Exception { public InvalidAgeException() {} }<br>void CheckAge(int age) { if(age < 0 || age > 120) throw new InvalidAgeException(); }
Step-by-Step Solution
Solution:
  1. Step 1: Verify custom exception class definition

    The class inherits from Exception and has a constructor calling base(msg) to pass the message.
  2. Step 2: Check usage in method

    The method throws the exception with a message when age is invalid, which matches the requirement.
  3. Final Answer:

    Correct class inheritance, constructor, and usage with message -> Option A
  4. Quick Check:

    Inherit Exception + throw with message = D [OK]
Quick Trick: Inherit Exception, add constructor, throw with message [OK]
Common Mistakes:
MISTAKES
  • Not inheriting from Exception
  • Defining constructor as void method
  • Missing message in exception constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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