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:
Step 1: Verify custom exception class definition
The class inherits from Exception and has a constructor calling base(msg) to pass the message.
Step 2: Check usage in method
The method throws the exception with a message when age is invalid, which matches the requirement.
Final Answer:
Correct class inheritance, constructor, and usage with message -> Option A
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
Master "Exception Handling" in C Sharp (C#)
9 interactive learning modes - each teaches the same concept differently