Search code examples
javaexceptionvavr

Why does vavr's Try container catches Throwable but not Exception?


I'm not an expert in java's type system and exception handling. But i found in SO that we should only catch exceptions but not throwable's.

Here is the link: Difference between using Throwable and Exception in a try catch

In Vavr's library i found this source code:

public interface Try<T> extends Value<T>, Serializable {
    long serialVersionUID = 1L;

    static <T> Try<T> of(CheckedFunction0<? extends T> supplier) {
        Objects.requireNonNull(supplier, "supplier is null");

        try {
            return new Try.Success(supplier.apply());
        } catch (Throwable var2) {
            return new Try.Failure(var2);
        }
    }
}

Would i have any issues in future if i will use this container? Will i miss some critical exceptions that may occur during execution of 'of' function?


Solution

  • The reason that Throwable was used instead of Exception, is because we want our Try objects to also catch Errors. This his how the inheritance model of Exceptions and Errors looks like:

    enter image description here

    If we only catch Exceptions, an IOError would crash our code and prevent us from using the strength of a Try chain:

    Try.of(() -> throw new IOError(null))
      .onFailure(() -> /* Do something to fix the IOError */);
    

    When catching Throwable, this IOError will be caught, and we will be able to execute the onFailure method. If we only catch Exception, the execution would have stopped on line one, and the onFailure would never be executed.