top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

VaVr Library in Java : Try Example


Vavr Try functionality can be used to handle the exceptions and continue with the flow.

We can check by wrapping the method return value in a Try clause and check whether the request was executed successfully or with failure.



import io.vavr.control.Try;

public class VavrExample {
  public static void main(String[] args) {
    // Call a method that may throw an exception
    String input = "10";
    Try<Integer> result = parseInput(input);

    // Handle the result using Vavr's Try class
    result.onSuccess(value -> System.out.println("Parsed value: " + value))
          .onFailure(error -> System.out.println("Error: " + error.getMessage()));
  }

  public static Try<Integer> parseInput(String input) {
    return Try.of(() -> Integer.parseInt(input));
  }
}

In this example, we have a parseInput() method that takes a string input and attempts to parse it as an integer using Integer.parseInt(). However, this method may throw a NumberFormatException if the input cannot be parsed.

To handle this potential exception in a functional way, we use Vavr's Try class to wrap the call to Integer.parseInt() in a Try.of() method. This returns a Try<Integer> object that represents either the result of the operation (an Integer) or an exception (a Throwable).

In the main method, we call parseInput() with a valid input (the string "10") and store the result in a Try<Integer> variable called result. We then use the onSuccess() and onFailure() methods provided by the Try class to handle the result.

If the result was successful (i.e. no exception was thrown), the onSuccess() method will be called with the parsed integer value as a parameter. We simply print this value to the console in this example.

If the result was a failure (i.e. an exception was thrown), the onFailure() method will be called with the exception object as a parameter. We simply print the exception message to the console in this example.

By using Vavr's Try class, we can handle exceptions in a more functional way that avoids the need for traditional try-catch blocks. This can make our code more concise and easier to reason about.

216 views

Recent Posts

See All

Kommentare


bottom of page