TheTry type represents a computation that may fail during evaluation by raising an exception. It holds either a successfully computed value or the exception that was thrown. This is similar to thescala.util.Either type, but with different semantics.
Instances ofTry[T] are an instance of eitherscala.util.Success[T] orscala.util.Failure[T].
For example, consider a computation that performs division on user-defined input.Try can reduce or eliminate the need for explicit exception handling in all of the places where an exception might be thrown.
Example:
import scala.io.StdInimport scala.util.{Try, Success, Failure}def divide: Try[Int] = { val dividend = Try(StdIn.readLine("Enter an Int that you'd like to divide:\n").toInt) val divisor = Try(StdIn.readLine("Enter an Int that you'd like to divide by:\n").toInt) val problem = dividend.flatMap(x => divisor.map(y => x/y)) problem match { case Success(v) => println("Result of " + dividend.get + "/"+ divisor.get +" is: " + v) Success(v) case Failure(e) => println("You must've divided by zero or entered something that's not an Int. Try again!") println("Info from the exception: " + e.getMessage) divide }}An important property ofTry shown in the above example is its ability topipeline, or chain, operations, catching exceptions along the way. TheflatMap andmap combinators in the above example each essentially pass off either their successfully completed value, wrapped in theSuccess type for it to be further operated upon by the next combinator in the chain, or the exception wrapped in theFailure type usually to be simply passed on down the chain. Combinators such asrecover andrecoverWith are designed to provide some type of default behavior in the case of failure.
Note: only non-fatal exceptions are caught by the combinators onTry (seescala.util.control.NonFatal). Serious system errors, on the other hand, will be thrown.
Note:: all Try combinators will catch exceptions and return failure unless otherwise specified in the documentation.
We need a whole WithFilter class to honor the "doesn't create a new collection" contract even though it seems unlikely to matter much in a collection with max size 1.
Applies the given partial function to the value from thisSuccess or returns this if this is aFailure.
Applies the given partial function to the value from thisSuccess or returns this if this is aFailure.
Inverts thisTry.
Inverts thisTry. If this is aFailure, returns its exception wrapped in aSuccess. If this is aSuccess, returns aFailure containing anUnsupportedOperationException.
Converts this to aFailure if the predicate is not satisfied.
Returns the given function applied to the value from thisSuccess or returns this if this is aFailure.
Returns the given function applied to the value from thisSuccess or returns this if this is aFailure.
Transforms a nestedTry, ie, aTry of typeTry[Try[T]], into an un-nestedTry, ie, aTry of typeTry[T].
Transforms a nestedTry, ie, aTry of typeTry[Try[T]], into an un-nestedTry, ie, aTry of typeTry[T].
Appliesfa if this is aFailure orfb if this is aSuccess.
Appliesfa if this is aFailure orfb if this is aSuccess. Iffb is initially applied and throws an exception, thenfa is applied with this exception.
the function to apply if this is aFailure
the function to apply if this is aSuccess
the results of applying the function
val result: Try[Int] = Try { string.toInt }log(result.fold( ex => "Operation failed with " + ex, v => "Operation produced value: " + v))Applies the given functionf if this is aSuccess, otherwise returnsUnit if this is aFailure.
Applies the given functionf if this is aSuccess, otherwise returnsUnit if this is aFailure.
Note: Iff throws, then this method may throw an exception.
Returns the value from thisSuccess or throws the exception if this is aFailure.
Returns the value from thisSuccess or throws the exception if this is aFailure.
Returns the value from thisSuccess or the givendefault argument if this is aFailure.
Returns the value from thisSuccess or the givendefault argument if this is aFailure.
Note:: This will throw an exception if it is not a success and default throws an exception.
Returnstrue if theTry is aFailure,false otherwise.
Returnstrue if theTry is aSuccess,false otherwise.
Maps the given function to the value from thisSuccess or returns this if this is aFailure.
Maps the given function to the value from thisSuccess or returns this if this is aFailure.
Returns thisTry if it's aSuccess or the givendefault argument if this is aFailure.
Returns thisTry if it's aSuccess or the givendefault argument if this is aFailure.
Applies the given functionf if this is aFailure, otherwise returns this if this is aSuccess.
Applies the given functionf if this is aFailure, otherwise returns this if this is aSuccess. This is like map for the exception.
Applies the given functionf if this is aFailure, otherwise returns this if this is aSuccess.
Applies the given functionf if this is aFailure, otherwise returns this if this is aSuccess. This is likeflatMap for the exception.
ReturnsLeft withThrowable if this is aFailure, otherwise returnsRight withSuccess value.
ReturnsLeft withThrowable if this is aFailure, otherwise returnsRight withSuccess value.
ReturnsNone if this is aFailure or aSome containing the value if this is aSuccess.
ReturnsNone if this is aFailure or aSome containing the value if this is aSuccess.
Completes thisTry by applying the functionf to this if this is of typeFailure, or conversely, by applyings if this is aSuccess.
Completes thisTry by applying the functionf to this if this is of typeFailure, or conversely, by applyings if this is aSuccess.
Creates a non-strict filter, which eventually converts this to aFailure if the predicate is not satisfied.
Creates a non-strict filter, which eventually converts this to aFailure if the predicate is not satisfied.
Note: unlike filter, withFilter does not create a new Try. Instead, it restricts the domain of subsequentmap,flatMap,foreach, andwithFilter operations.
As Try is a one-element collection, this may be a bit overkill, but it's consistent with withFilter on Option and the other collections.
the predicate used to test elements.
an object of classWithFilter, which supportsmap,flatMap,foreach, andwithFilter operations. All these operations apply to those elements of this Try which satisfy the predicatep.
The name of the nth element of this product, 0-based.
The name of the nth element of this product, 0-based. In the default implementation, an empty string.
the index of the element name to return
the name of the specified element
IndexOutOfBoundsExceptionif then is out of range(n < 0 || n >= productArity).
An iterator over the names of all the elements of this product.
An iterator over the names of all the elements of this product.
An iterator over all the elements of this product.
An iterator over all the elements of this product.
in the default implementation, anIterator[Any]
A string used in thetoString methods of derived classes.
A string used in thetoString methods of derived classes. Implementations may override this method to prepend a string prefix to the result oftoString methods.
in the default implementation, the empty string
Checks whether this instance can possibly equalthat.
Checks whether this instance can possibly equalthat.
A method that should be called from every well-designed equals method that is open to be overridden in a subclass. SeeProgramming in Scala, Chapter 28 for discussion and design.
the value being probed for possible equality
true if this instance can possibly equalthat, otherwise false
The size of this product.
The size of this product.
for a productA(x1, ..., xk), returnsk
The nth element of this product, 0-based.
The nth element of this product, 0-based. In other words, for a productA(x1, ..., xk), returnsx(n+1) where0 <= n < k.
the index of the element to return
the elementn elements after the first element
IndexOutOfBoundsExceptionif then is out of range(n < 0 || n >= productArity).