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
public void processPayment(double amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be non-negative");
}
// process payment
}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.
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?