Try Pattern

  • defensive programming technique where you attempt an operation that might fail and report success/failure using a return value (usually true or false), rather than relying on exceptions

  • useful for expected, frequent errors like parsing user input or looking up values in collections.

  • Common in C# but not java

    • will need to build helper methods

Impl Java

  • Use of optional

  public static Optional<Integer> tryParseInt(String s) {
    try {
         return Optional.of(Integer.parseInt(s));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
  }

    // Usage:
    Optional<Integer> maybeInt = tryParseInt("123");
    maybeInt.ifPresentOrElse(
            i -> System.out.println("Parsed: " + i),
            () -> System.out.println("Invalid input")
    );
  • Use boolean

Last updated

Was this helpful?