Bird
0
0

You want to create a custom unchecked exception named InvalidDataException. Which is the correct way to define it?

hard📝 Application Q15 of 15
Java - Custom Exceptions
You want to create a custom unchecked exception named InvalidDataException. Which is the correct way to define it?
Apublic class InvalidDataException implements RuntimeException { public InvalidDataException(String message) { super(message); } }
Bpublic class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } }
Cpublic class InvalidDataException extends Exception { public InvalidDataException(String message) { super(message); } }
Dpublic class InvalidDataException extends Throwable { public InvalidDataException(String message) { super(message); } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand checked vs unchecked exceptions

    Unchecked exceptions extend RuntimeException, checked exceptions extend Exception.
  2. Step 2: Analyze each option

    public class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } } correctly extends RuntimeException with proper constructor. public class InvalidDataException extends Exception { public InvalidDataException(String message) { super(message); } } creates a checked exception. public class InvalidDataException implements RuntimeException { public InvalidDataException(String message) { super(message); } } tries to implement an exception class, which is invalid. public class InvalidDataException extends Throwable { public InvalidDataException(String message) { super(message); } } extends Throwable directly, which is not recommended for custom exceptions.
  3. Final Answer:

    public class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } } -> Option B
  4. Quick Check:

    Unchecked exception = extends RuntimeException [OK]
Quick Trick: Unchecked exceptions extend RuntimeException, not Exception [OK]
Common Mistakes:
  • Extending Exception for unchecked exceptions
  • Trying to implement exception classes
  • Extending Throwable directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes