Exceptions · interview question
You are designing a method that takes a user ID as input. What should you do if the ID is null?
Multiple choiceMediumchapter-6-curatedpremiumexceptionsfail-fast-validation
public void setUser(String userId) {
if (userId == null) {
throw new NullPointerException("User ID cannot be null");
}
// set user logic
}Answer and explanation
Correct answer
C. Throw a NullPointerException
Why
Throwing a NullPointerException when encountering a null user ID aligns with fail-fast principles. It immediately indicates that the input is invalid, preventing further processing and potential errors.
Test yourself on Exceptions
A free test with instant, explained results. No account needed.
More Exceptions questions
- When designing a Java API, how should exceptions be documented?
- Why can catching the Exception class in Java become a real problem?
- How can fail-fast validation impact the design of a Java class intended for secure financial transactions?
- Why can overusing checked exceptions in a library become a problem in production code?
- In which scenario does exception wrapping make code more reliable?
- What role does the 'finally' block serve in Java exception handling?