Alexander Kondaurov
Alexander Kondaurov

Reputation: 4123

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?

Upvotes: 2

Views: 1141

Answers (3)

Titulum
Titulum

Reputation: 11476

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.

Upvotes: 3

Carcigenicate
Carcigenicate

Reputation: 45750

Note what the answer in the linked post says:

You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong.

Emphasis mine.

That is likely the intent here. This is a try wrapper meant to handle everything and let the user decide what they want to deal with and how. It seems they're going for a construct like Scala's Try to let you handle exceptions without manually catching them. For that to work and be consistent, everything should be handled the same way, or you'd have some exceptions needing to be caught, and others that are handled as this class intends.

As for

Will i miss some critical exceptions that may occur during execution of 'of' function?

You won't miss them. They're be returned wrapped in a Try.Failure, and you can handle them then after receiving the error.

Upvotes: 5

Adam Siemion
Adam Siemion

Reputation: 16039

Throwable is a superclass of Exception, meaning catch (Throwable var) catches Exceptions as well. Therefore the code in vavr is correct - whenever there is any Throwable thrown it will be wrapped in a Try.Failure.

Upvotes: 5

Related Questions