APIdia Launch Partner
Top Description Fields Constructors Methods
net.ucanaccess.util

public final Class Try<V, EC extends Throwable>

extends Object
Class Inheritance
Annotations
@SuppressWarnings:java:S119, java:S1181
Type Parameters
<V>
the type of the optional value from the code block executed within @code try}
<EC>
the type of exception, if any, thrown by the executed code block.
Imports
java.util.Objects, java.util.function.Function, .Supplier

Fluent-style try-catch handling.

Try objects are constructed using the catching(IThrowingRunnable) or catching(IThrowingSupplier) factories from code blocks which may or may not throw checked or unchecked (run-time) exceptions.
The exception is dealt with inside the Try instance. The class provides methods to access the result, access the exception, use an alternative result if an exception occurred, transform the result to another result amongst other methods.
Try instances are immutable.

Usage example:

    // In this sample we query the last modification timestamp of a path p.
    // The API throws IOException (if an I/O error occurs).

    Path p = Path.of("a_path");

    // Code using a conventional try/catch construct looks like this:
    String str1 = null;
    try {
        str1 = Files.getLastModifiedTime(p).toString();
    } catch (IOException ex) {
        str1 = "unknown";
    }
    System.out.println("1: File time is: " + str1);

    // The same using Try:
    Try<FileTime, IOException> tc1 = Try.catching(() -> Files.getLastModifiedTime(p));

    // Perform a transformation of the internal value. Here FileTime is mapped to its string representation.
    Try<String, Throwable> tc2 = tc1.map(FileTime::toString);

    String str2 = tc2.orElse("unknown");
    System.out.println("2: File time is: " + str2);

    // The same on a single line:
    System.out.println("3: File time is: " + Try.catching(() -> Files.getLastModifiedTime(p).toString()).orElse("unknown"));

    // Similarly the class supports try-with-resources scenarios such as:
    List<File> files = Try.withResources(() -> Files.walk(p), w -> {
        return w.filter(Files::isRegularFile)
                .map(Path::toFile)
                .collect(Collectors.toList());
    }).orIgnore();
Author
Markus Spann
Since
v5.1.0

Field Summary

Modifier and TypeField and Description
private final EC
t

The immutable exception or null if value retrieval succeeded without exception.

private final V
val

The immutable value or null if an exception occurred during retrieval.

Constructor Summary

AccessConstructor and Description
private
Try(IThrowingSupplier<V, EC>
a throwing supplier
catchable
)

Creates a new instance from a throwing supplier.

private
Try(V
value, may be null
val
,
EC
exception, may be null
ex
)

Creates a new instance from a value and an exception.

Method Summary

Modifier and TypeMethod and Description
public static <
the type of value supplied by the supplier
R
,
the type of exception, if any, thrown by the supplier
EC extends Throwable
>
Try<R, EC>

Returns:

new instance
catching
(IThrowingSupplier<R, EC>
a throwing supplier
catchable
)

Creates a new instance from a throwing Supplier.

public static <
the type of exception, if any, thrown by the runnable
EC extends Throwable
>
Try<Void, EC>

Returns:

new instance
catching
(IThrowingRunnable<EC>
a throwing runnable
catchable
)

Creates a new instance from a throwing Runnable.

private static <
the type of Throwable
T extends Throwable
>
RuntimeException

Returns:

run-time exception
doThrow
(Throwable
throwable
t
)

Performs a vacuous cast on a Throwable to evade the Java checked exception mechanism.

public V

Returns:

the successful value
get
()

Gets the value or re-throws the exception if one has occurred.

public EC

Returns:

exception
getException
()

Gets the exception or null if none has occurred.

pack-priv boolean

Returns:

true if an exception has occurred, false otherwise.
hasThrown
()

Indicates whether an exception has occurred.

public <
the type result produced by the mapper
V1
,
the type of exception thrown by the mapper
E1 extends Throwable
>
Try<V1, E1>

Returns:

new instance with transformed value
map
(Function<? super V, ? extends V1>
mapping function
mapper
)

Performs a transformation on the internal value, if the source object does not have an exception.

public V

Returns:

the successful value, otherwise the other value
orElse
(V
the value to be returned, if an exception has occurred. May be null.
other
)

Returns the successful value or if an exception has occurred returns other.

public void
orElse(IThrowingConsumer<Throwable, Throwable>
consumer to execute in case of exception. The exception object is passed to the consumer.
consumer
)

Executes consumer with the exception as parameter, if an exception has occurred.

public V

Returns:

the successful value or value returned by the function
orElseApply
(IThrowingFunction<Throwable, V, Throwable>
function to execute in case of exception. The exception object is passed to the function.
function
)

If an exception has occurred, executes function with the exception as parameter to retrieve an alternative value, otherwise returns the value.

public V

Returns:

the successful value or value returned by the supplier
orElseGet
(IThrowingSupplier<V, Throwable>
supplier that supplies an alternative value
supplier
)

If an exception has occurred, executes supplier to get an alternative value, otherwise returns the value.

public V

Returns:

the successful value or null
orIgnore
()

Returns the value on success or null ignoring any prior exception.

public V

Returns:

the successful value
orThrow
()

Returns the successful value or throws the exception that occurred earlier.

public <
the type of exception returned by function
T2 extends Throwable
>
V

Returns:

the successful value
orThrow
(Function<Throwable, T2>
non-null function to provide an exception. The previous exception object is passed to the function.
function
)

Returns the successful value or throws the exception returned by function.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

public static <
the type of resource (must implement AutoCloseable)
R extends AutoCloseable
,
the type of exception, if any, thrown by the resource supplier
ES extends Throwable
,
the type of value returned by the function
V
,
the type of exception, if any, thrown by the function
EC extends Throwable
>
Try<V, EC>

Returns:

new instance
withResources
(IThrowingSupplier<R, ES>
the resource supplier
resourceSupplier
,
IThrowingFunction<R, V, EC>
the function executed on the resource
catchable
)

Try-with-resources support for a single resource.

public static <R extends AutoCloseable, ES extends Throwable, EC extends Throwable> Try<Void, EC>
withResources(IThrowingSupplier<R, ES> resourceSupplier, IThrowingConsumer<R, EC> catchable)

Try-with-resources support for a single resource with a Void (no) result.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

tback to summary
private final EC t

The immutable exception or null if value retrieval succeeded without exception.

valback to summary
private final V val

The immutable value or null if an exception occurred during retrieval.

Constructor Detail

Tryback to summary
private Try(IThrowingSupplier<V, EC> catchable)

Creates a new instance from a throwing supplier.

Parameters
catchable:IThrowingSupplier<V, EC>

a throwing supplier

Tryback to summary
private Try(V val, EC ex)

Creates a new instance from a value and an exception.

Parameters
val:V

value, may be null

ex:EC

exception, may be null

Method Detail

catchingback to summary
public static <R, EC extends Throwable> Try<R, EC> catching(IThrowingSupplier<R, EC> catchable)

Creates a new instance from a throwing Supplier.

Parameters
<R>
the type of value supplied by the supplier
<EC>
the type of exception, if any, thrown by the supplier
catchable:IThrowingSupplier<R, EC>

a throwing supplier

Returns:Try<R, EC>

new instance

catchingback to summary
public static <EC extends Throwable> Try<Void, EC> catching(IThrowingRunnable<EC> catchable)

Creates a new instance from a throwing Runnable.

Parameters
<EC>
the type of exception, if any, thrown by the runnable
catchable:IThrowingRunnable<EC>

a throwing runnable

Returns:Try<Void, EC>

new instance

doThrowback to summary
private static <T extends Throwable> RuntimeException doThrow(Throwable t) throws T

Performs a vacuous cast on a Throwable to evade the Java checked exception mechanism.

Parameters
<T>
the type of Throwable
t:Throwable

throwable

Returns:RuntimeException

run-time exception

Annotations
@SuppressWarnings:unchecked
Exceptions
T:
throwable
getback to summary
public V get()

Gets the value or re-throws the exception if one has occurred.

Returns:V

the successful value

getExceptionback to summary
public EC getException()

Gets the exception or null if none has occurred.

Returns:EC

exception

hasThrownback to summary
pack-priv boolean hasThrown()

Indicates whether an exception has occurred.

Returns:boolean

true if an exception has occurred, false otherwise.

mapback to summary
public <V1, E1 extends Throwable> Try<V1, E1> map(Function<? super V, ? extends V1> mapper)

Performs a transformation on the internal value, if the source object does not have an exception.

Parameters
<V1>
the type result produced by the mapper
<E1>
the type of exception thrown by the mapper
mapper:Function<? super V, ? extends V1>

mapping function

Returns:Try<V1, E1>

new instance with transformed value

orElseback to summary
public V orElse(V other)

Returns the successful value or if an exception has occurred returns other.

Parameters
other:V

the value to be returned, if an exception has occurred. May be null.

Returns:V

the successful value, otherwise the other value

orElseback to summary
public void orElse(IThrowingConsumer<Throwable, Throwable> consumer)

Executes consumer with the exception as parameter, if an exception has occurred.
If an exception occurs during execution of the throwing consumer, that exception is thrown.

Parameters
consumer:IThrowingConsumer<Throwable, Throwable>

consumer to execute in case of exception. The exception object is passed to the consumer.

orElseApplyback to summary
public V orElseApply(IThrowingFunction<Throwable, V, Throwable> function)

If an exception has occurred, executes function with the exception as parameter to retrieve an alternative value, otherwise returns the value.

Parameters
function:IThrowingFunction<Throwable, V, Throwable>

function to execute in case of exception. The exception object is passed to the function.

Returns:V

the successful value or value returned by the function

orElseGetback to summary
public V orElseGet(IThrowingSupplier<V, Throwable> supplier)

If an exception has occurred, executes supplier to get an alternative value, otherwise returns the value.

Parameters
supplier:IThrowingSupplier<V, Throwable>

supplier that supplies an alternative value

Returns:V

the successful value or value returned by the supplier

orIgnoreback to summary
public V orIgnore()

Returns the value on success or null ignoring any prior exception.

Returns:V

the successful value or null

orThrowback to summary
public V orThrow()

Returns the successful value or throws the exception that occurred earlier.

Returns:V

the successful value

orThrowback to summary
public <T2 extends Throwable> V orThrow(Function<Throwable, T2> function) throws Function-:T2

Returns the successful value or throws the exception returned by function.
The function is applied if this object has previously thrown and must provide an exception.

Parameters
<T2>
the type of exception returned by function
function:Function<Throwable, T2>

non-null function to provide an exception. The previous exception object is passed to the function.

Returns:V

the successful value

Exceptions
Function-:T2:
the exception returned by function
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object. Satisfying this method's contract implies a non-null result must be returned.

Annotations
@Override
withResourcesback to summary
public static <R extends AutoCloseable, ES extends Throwable, V, EC extends Throwable> Try<V, EC> withResources(IThrowingSupplier<R, ES> resourceSupplier, IThrowingFunction<R, V, EC> catchable)

Try-with-resources support for a single resource.
The resource is created and returned by resourceSupplier and processed in catchable.
If an exception occurs during resource creation, this execution is thrown and thus processing ends.

Parameters
<R>
the type of resource (must implement AutoCloseable)
<ES>
the type of exception, if any, thrown by the resource supplier
<V>
the type of value returned by the function
<EC>
the type of exception, if any, thrown by the function
resourceSupplier:IThrowingSupplier<R, ES>

the resource supplier

catchable:IThrowingFunction<R, V, EC>

the function executed on the resource

Returns:Try<V, EC>

new instance

Annotations
@SuppressWarnings:try
withResourcesback to summary
public static <R extends AutoCloseable, ES extends Throwable, EC extends Throwable> Try<Void, EC> withResources(IThrowingSupplier<R, ES> resourceSupplier, IThrowingConsumer<R, EC> catchable)

Try-with-resources support for a single resource with a Void (no) result.