import com.google.common.base.Preconditions; import java.util.List; public class Example { public static void main(String[] args) { ListmyList = List.of("one", "two", "three"); try { int index = 3; Preconditions.checkPositionIndex(index, myList.size()); String value = myList.get(index); System.out.println("Value at index " + index + " is: " + value); } catch (IndexOutOfBoundsException ex) { System.out.println("Invalid index: " + ex.getMessage()); } } }
import com.google.common.base.Preconditions; public class Example { public static void main(String[] args) { String myString = "example string"; try { int index = 15; Preconditions.checkPositionIndex(index, myString.length()); char value = myString.charAt(index); System.out.println("Value at index " + index + " is: " + value); } catch (IndexOutOfBoundsException ex) { System.out.println("Invalid index: " + ex.getMessage()); } } }In this example, `checkPositionIndex` is used to validate the index `15` against the length of the string. Since the string has only `14` characters, this index is invalid and an `IndexOutOfBoundsException` is thrown. Overall, the `com.google.common.base.Preconditions` class provides a set of utility methods to check preconditions for methods arguments and fails fast with descriptive exceptions.