Skip to content
Sharp

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
java
public void setUser(String userId) {
  if (userId == null) {
    throw new NullPointerException("User ID cannot be null");
  }
  // set user logic
}
Choose one answer
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.

Start free test
All Exceptions questions →