Module: | Arrays, Strings & Exception Handling
Q49: Consider the following statements regarding Custom (User-Defined) Exceptions in Java:
1. To create a custom Checked Exception that forces mandatory compile-time handling, the developer must structurally inherit their custom class directly from java.lang.Exception.
2. To create a custom Unchecked Exception that inherently bypasses compiler mandates, the developer must structurally inherit their custom class directly from java.lang.RuntimeException.
3. Custom exception classes are strictly forbidden from possessing parameterized constructors or custom instance variables; they can only rely on the default getMessage() implementation inherited from Throwable.
Which of the above statements is/are correct?
2. To create a custom Unchecked Exception that inherently bypasses compiler mandates, the developer must structurally inherit their custom class directly from java.lang.RuntimeException.
3. Custom exception classes are strictly forbidden from possessing parameterized constructors or custom instance variables; they can only rely on the default getMessage() implementation inherited from Throwable.
Which of the above statements is/are correct?
✅ Correct Answer: A
🎯 Quick Answer:
The correct combination is 1 and 2. Statement 3 is incorrect because custom exceptions are fully-fledged Java classes. They can absolutely contain parameterized constructors, custom instance variables (like an error code integer), and customized getter methods to provide rich diagnostic data to the catching block.Structural Breakdown: The creation is structurally simple: 'public class AgeLimitException extends RuntimeException { public AgeLimitException(String message) { super(message); } }'. Historical/Related Context: In large-scale enterprise microservices, tracking errors is immensely difficult.
If a banking app throws a generic 'IllegalArgumentException', the debugging team has no idea which module failed.
By utilizing highly specific custom exceptions, the logs instantly reveal the exact domain and business logic boundary that was breached.
Causal Reasoning: When inheriting from Exception or RuntimeException, it is an industry best practice to provide a constructor that takes a String message and passes it to the parent constructor via super(message). This ensures that the custom error message is seamlessly integrated into the JVM's native stack trace generation mechanisms.