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
public class TryParseUtil {
public static boolean tryParseInt(String s, AtomicInteger result) {
try {
result.set(Integer.parseInt(s));
return true;
} catch (NumberFormatException e) {
result.set(0); // or leave it unchanged if you prefer
return false;
}
}
}
// Usage:
AtomicInteger result = new AtomicInteger();
if (TryParseUtil.tryParseInt("123", result)) {
System.out.println("Parsed: " + result.get());
} else {
System.out.println("Invalid input");
}
Last updated
Was this helpful?