Groovy IllegalArgumentException
A ticket order requires at least one seat. Reject invalid arguments before updating availability.
A simple example
IllegalArgumentException
- Start with A function needs a positive count
- Do this Supply 0
- Result Argument rejected
Syntax
if (quantity <= 0) throw new IllegalArgumentException("Quantity must be positive")
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyReject an empty ticket order
A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.
def quantity = 0
try {
if (quantity <= 0) throw new IllegalArgumentException("Quantity must be positive")
} catch (IllegalArgumentException invalid) {
println("Check quantity")
}
Check quantity
Zero seats violates the precondition. The caller handles the validation failure by asking for a corrected quantity.
Accept a team entry
A team asks for four places at the Saturday session. The workshop accepts a positive number of places. Reject zero before saving the reservation.
Stop an empty reservation
A booking form sends zero places when the quantity field is cleared. The workshop accepts a positive number of places. Reject zero before saving the reservation.
What to watch for
Catch only the failure you can recover from and preserve unrelated errors.