Interface ThrowingSupplier<T>

Type Parameters:
T - The type of results supplied by this supplier.
Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

A functional interface representing a supplier of results that may throw a checked exception.

This interface extends the standard Java Supplier pattern to allow the get() method to throw checked exceptions. This is useful when you need to pass suppliers that may throw exceptions (such as I/O operations) to methods that expect functional interfaces.

Features:
  • Functional interface - can be used with lambda expressions and method references
  • Exception support - allows checked exceptions to be thrown
  • Compatible with Supplier - can be used where Supplier is expected (exceptions are wrapped)
Use Cases:
  • Suppliers that perform I/O operations (file reading, network calls)
  • Suppliers that may throw business logic exceptions
  • Lazy initialization that may fail
  • Resource creation that may throw exceptions
Usage:

// Lambda with exception ThrowingSupplier<String> fileReader = () -> { return new String(Files.readAllBytes(Paths.get("data.txt"))); }; // Method reference ThrowingSupplier<Connection> dbConnection = dataSource::getConnection; // Usage in try-catch try { String content = fileReader.get(); } catch (Exception e) { // Handle exception }

Comparison with Supplier:
  • Supplier: Cannot throw checked exceptions (must catch and wrap)
  • ThrowingSupplier: Can throw checked exceptions directly
  • Supplier: Used for standard functional programming patterns
  • ThrowingSupplier: Used when operations may fail with checked exceptions
See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    get()
    Gets a result, potentially throwing a checked exception.
  • Method Details

    • get

      T get() throws Exception
      Gets a result, potentially throwing a checked exception.
      Example:

      ThrowingSupplier<String> supplier = () -> { if (fileNotFound) { throw new FileNotFoundException("File not found"); } return "content"; }; try { String result = supplier.get(); } catch (FileNotFoundException e) { // Handle exception }

      Returns:
      A result.
      Throws:
      Exception - If an error occurs during result computation.