Try: Capturing Exceptions as Values

Run code that throws, and keep the exception as a value you can map, chain and recover from.

Try at a glance

ModelsA value, or the exception that stopped the computation
ReplacesA try/catch block around a call that throws
Effect PathTryPath
InstancesFunctor, Applicative, Monad, MonadError<Throwable>, Foldable, Traverse
Choose it whenThe failure is an exception from code you call; otherwise Either, or compare every type in Choosing a Type

What You'll Learn

  • Turn a call that throws into a Try, and choose between Try.of and Try.attempt
  • Chain steps that can each throw, and say which exception reaches the end
  • Recover from a failure with a value, or with another attempt
  • Read a Try with a switch or fold
  • Hand a Try's failure to an Either chain through TryPath

See Example Code

The code on this page is TryBook.java: the page includes it, so the build compiles and runs it. TryBookTest.java holds what the page says each method does.


Exceptions as values

Much of the JDK reports failure by throwing: Integer.parseInt, new BigDecimal and Files.readString among them. A try/catch block splits the result in two, the value on one path and the exception in the catch block, so the outcome cannot be stored, passed to map or returned as one value. Try<T> runs the call and keeps what happened. A Success holds the value, and a Failure holds the exception the call threw. It is close to an Either whose left side is always an exception, with the try/catch written for you.

The code on this page uses these imports, with LineItem from the order records the Optics chapter introduces:

import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.hkt.trymonad.Try;

A wholesaler's feed sends order lines as text, such as LAMP,2,40.00. Reading one calls two methods that throw on text they cannot read, so Try.of runs them:

  // Integer.parseInt and new BigDecimal throw on text they cannot read
  static Try<LineItem> parseLine(String line) {
    return Try.of(
        () -> {
          String[] parts = line.split(",");
          return new LineItem(parts[0], Integer.parseInt(parts[1]), new BigDecimal(parts[2]));
        });
  }

    Try<LineItem> lamp = parseLine("LAMP,2,40.00");
    // Success(LineItem[sku=LAMP, quantity=2, price=40.00])
    Try<LineItem> misspelt = parseLine("LAMP,two,40.00");
    // Failure(java.lang.NumberFormatException: For input string: "two")

Try.of takes a Supplier, and a Supplier cannot throw a checked exception, so javac refuses a call such as Files.readString there, with "unreported exception IOException; must be caught or declared to be thrown":

Try<String> feed = Try.of(() -> Files.readString(Paths.get("feed.csv")));

Try.attempt takes a function that may throw one. MISSING_FEED names a file that does not exist:

  // Files.readString declares IOException, a checked exception
  static Try<String> readFeed(String file) {
    return Try.attempt(() -> Files.readString(Paths.get(file)));
  }

    Try<String> feed = readFeed(MISSING_FEED);
    // Failure(java.nio.file.NoSuchFileException: missing-feed.csv)

Both catch any Exception, checked or not, and so do Try's map, flatMap, recover and recoverWith when their function throws. A caught InterruptedException sets the thread's interrupt flag again. An Error, such as StackOverflowError, propagates out of them, as it passes a catch (Exception e) clause.

Chaining and recovering

On a Success, flatMap passes the value to a step that returns a Try of its own. On a Failure, the step never runs, and the first exception reaches the end:

  static Try<LineItem> requirePositivePrice(LineItem item) {
    return item.price().signum() > 0
        ? Try.success(item)
        : Try.failure(new IllegalArgumentException("price must be positive: " + item.price()));
  }

  static Try<LineItem> checkedLine(String line) {
    return parseLine(line).flatMap(TryBook::requirePositivePrice);
  }

    Try<LineItem> free = checkedLine("LAMP,2,0.00");
    // Failure(java.lang.IllegalArgumentException: price must be positive: 0.00)
    Try<LineItem> unread = checkedLine("LAMP,two,0.00");
    // Failure(java.lang.NumberFormatException: For input string: "two")

map changes a Success's value, and an exception its function throws becomes a Failure too. To leave the failure behind, recoverWith makes another attempt, and recover gives a value in its place:

  // Some feeds put a pound sign before the price, so try again without it
  static Try<BigDecimal> price(String text) {
    return Try.of(() -> new BigDecimal(text))
        .recoverWith(
            error ->
                text.startsWith("£")
                    ? Try.of(() -> new BigDecimal(text.substring(1)))
                    : Try.failure(error));
  }

    Try<BigDecimal> withSign = price("£40.00");
    // Success(40.00)
    Try<BigDecimal> unreadable = price("forty");
    // Failure(java.lang.NumberFormatException: ...)
    Try<String> noFeed = readFeed(MISSING_FEED).recover(error -> "");
    // Success()

A feed that cannot be read counts as empty here, so recover gives an empty String. Neither method runs its function on a Success, and an exception that function throws becomes the new Failure.

Reading a Try

A switch over the two cases reads the result, and the compiler checks that both are handled:

  static String describe(Try<LineItem> result) {
    return switch (result) {
      case Try.Success(LineItem item) -> item.quantity() + " x " + item.sku();
      case Try.Failure(Throwable cause) -> "unreadable line: " + cause.getMessage();
    };
  }

fold(onFailure, onSuccess) does the same with two functions, and takes the failure function first, as Either.fold takes the Left function first. get() returns the value or throws the exception, so it is declared throws Throwable and a caller must catch Throwable; keep it for tests.

Creating instances

Try.success(value) and Try.failure(throwable) build either case directly. A Success always holds a value, so Try.success(null) throws NullPointerException. A function given to Try.of, map or recover that returns null gives a Failure holding a NullPointerException. NullAway flags one given to Try.of only with the options in What a nullness checker sees. A flatMap or recoverWith function that returns null in place of a Try throws KindUnwrapException. Values, never null has the rule for every type.

Methods

MethodWhat it does
Try.of(supplier)Runs the supplier now, giving a Success of its value, or a Failure of the Exception it throws
Try.attempt(supplier)The same, for a supplier that throws a checked exception
Try.success(value), Try.failure(throwable)Build either case directly
isSuccess(), isFailure()Say which case it holds
map(f)Changes a Success's value; an exception f throws becomes a Failure
flatMap(f)Runs a step that gives a Try; a Failure passes through
recover(f)Turns a Failure into a Success of the value f gives
recoverWith(f)Turns a Failure into the Try that f gives
fold(onFailure, onSuccess)Turns either case into one result
match(onSuccess, onFailure)Runs an action for the case it holds, and takes the success action first
orElse(other), orElseGet(supplier)Return the value, or a fallback
get()Returns the value, or throws the exception it holds
toEither(f)Gives an Either whose Left is f applied to the exception
toOptional()Gives a Success's value as an Optional, or an empty one for a Failure

Releases before 0.5.0 had a fold that took the success function first. A call written for it compiles against this one wherever both functions accept either argument, and runs them the wrong way round. Before you move such code here, run MigrateDeprecationsTo0_5_0 on it while it still compiles against 0.4.x, as To 0.6.0 explains. foldFailureFirst, the same method under its 0.5.0 name, is deprecated for removal in 0.7.0.

On a TryPath

Application code can hold the same steps on a TryPath. Path.tryPath takes a Try, via chains a step, and toEitherPath turns the exception into an error of your own. From there, via chains on to EitherPath steps with the same error type, here String. These are the extra imports:

import org.higherkindedj.hkt.effect.EitherPath;
import org.higherkindedj.hkt.effect.Path;
  static EitherPath<String, LineItem> lineOrReason(String line) {
    return Path.tryPath(parseLine(line))
        .via(item -> Path.tryPath(requirePositivePrice(item)))
        .toEitherPath(error -> "skipped " + line + ": " + error.getMessage());
  }

    EitherPath<String, LineItem> skipped = lineOrReason("LAMP,2,0.00");
    // EitherPath(Left(skipped LAMP,2,0.00: price must be positive: 0.00))

Working with Kind

Generic code, written once for any container, takes Try through its MonadError instance, whose error type is Throwable, as MonadError shows. The instance works over Kind<TryKind.Witness, A>, so you widen a Try to pass it in, and narrow the result to read it. These are the extra imports:

import static org.higherkindedj.hkt.instances.Witnesses.try_;
import static org.higherkindedj.hkt.trymonad.TryKindHelper.TRY;

import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.MonadError;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.trymonad.TryKind;
    MonadError<TryKind.Witness, Throwable> tries = Instances.monadError(try_());

    Kind<TryKind.Witness, LineItem> parsed = TRY.widen(parseLine("LAMP,two,40.00"));
    Kind<TryKind.Witness, LineItem> checked =
        tries.flatMap(item -> TRY.widen(requirePositivePrice(item)), parsed);
    Kind<TryKind.Witness, String> answer =
        tries.handleError(
            tries.map(item -> "read " + item.sku(), checked),
            error -> "skipped: " + error.getClass().getSimpleName());

    Try<String> reply = TRY.narrow(answer);
    // Success(skipped: NumberFormatException)

The line could not be read, so flatMap never ran the price check, and handleError turned the exception into a reply. Widening allocates nothing: Try implements TryKind itself, so widen checks for null and returns the same object.

When to use Try

You needUse
The exception from a JDK or library call, kept as a valueTry
The same steps as a fluent chain in application codeTryPath
An error type of your own, rather than ThrowableEither, converting with toEither
Every error from checks that do not depend on one anotherValidated
Work described now and run later, rather than at onceIO or VTask

Hands-On Learning

Practise recovering from errors with MonadError, and capturing an exception with Try.of, in Tutorial 05: MonadError Handling (7 exercises).


Previous: Accumulating Assembly Next: EitherOrBoth