Throwing Exceptions When Preconditions or Postconditions Are Not Met
When their preconditions or postconditions are not met, methods typically throw exceptions. As an example, examine String
method charAt
, which has one int
parameter—an index in the String
. For a precondition, method charAt
assumes that index
is greater than or equal to zero and less than the length of the String
. If the precondition is met, the postcondition states that the method will return the character at the position in the String
specified by the parameter index
. Otherwise, the method throws an IndexOutOfBoundsException
. We trust that method charAt
satisfies its postcondition, provided that we meet the precondition. We need not be concerned with the details of how the ...
Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.