Skip to content
Sharp

Exceptions · interview question

Consider the following Java method signature. What should you do if 'amount' is negative? public void processPayment(double amount)?

Multiple choiceMediumchapter-6-curatedpremiumexceptionsfail-fast-validation
java
public void processPayment(double amount) {
  if (amount < 0) {
    throw new IllegalArgumentException("Amount must be non-negative");
  }
  // process payment
}
Choose one answer
Answer and explanation

Correct answer

B. Throw an IllegalArgumentException

Why

Throwing an IllegalArgumentException when 'amount' is negative is an example of fail-fast validation. This prevents invalid input from being processed further, ensuring that only valid state is used in the method.

Test yourself on Exceptions

A free test with instant, explained results. No account needed.

Start free test
All Exceptions questions →