Is it possible to declare that a Supplier<T> needs to throw an Exception?

Related searches

So I am trying to refactor the following code:

/**
 * Returns the duration from the config file.
 * 
 * @return  The duration.
 */
private Duration durationFromConfig() {
    try {
        return durationFromConfigInner();
    } catch (IOException ex) {
        throw new IllegalStateException("The config file (\"" + configFile + "\") has not been found.");
    }
}

/**
 * Returns the duration from the config file.
 * 
 * Searches the log file for the first line indicating the config entry for this instance.
 * 
 * @return  The duration.
 * @throws FileNotFoundException If the config file has not been found.
 */
private Duration durationFromConfigInner() throws IOException {
    String entryKey = subClass.getSimpleName();
    configLastModified = Files.getLastModifiedTime(configFile);
    String entryValue = ConfigFileUtils.readFileEntry(configFile, entryKey);
    return Duration.of(entryValue);
}

I came up with the following to start of with:

private <T> T getFromConfig(final Supplier<T> supplier) {
    try {
        return supplier.get();
    } catch (IOException ex) {
        throw new IllegalStateException("The config file (\"" + configFile + "\") has not been found.");
    }
}

However, it does not compile (obviously), as Supplier cannot throw an IOException. Is there any way I can add that to the method declaration of getFromConfig?

Or is the only way to do it like the following?

@FunctionalInterface
public interface SupplierWithIO<T> extends Supplier<T> {
    @Override
    @Deprecated
    default public T get() {
        throw new UnsupportedOperationException();
    }

    public T getWithIO() throws IOException;
}

Update, I just realised that the Supplier interface is a really simple one, as in it has only the get() method. The original reason why I extended Supplier is to preverse the basic functionality, like the default methods for example.


How to handle (long-term) vendor declarations (LTVDs) – Law firm , Points to consider. I was asked to present a supplier's declaration. What is it? The supplier's declaration is a document used mainly in EU internal trade to prove� It is also possible to declare preferential origin for goods that have previously been imported from a country with which the EU has concluded a preferential agreement (e.g. Switzerland) with a proof of preference – in such cases, the supplier’s declaration must state the country of origin specified in the corresponding proof of preference


In the lambda mailing list this was throughly discussed. As you can see Brian Goetz suggested there that the alternative is to write your own combinator:

Or you could write your own trivial combinator:

static<T> Block<T> exceptionWrappingBlock(Block<T> b) {
     return e -> {
         try { b.accept(e); }
         catch (Exception e) { throw new RTE(e); }
     };
}

You can write it once, in less that the time it took to write your original e-mail. And similarly once for each kind of SAM you use.

I'd rather we look at this as "glass 99% full" rather than the alternative. Not all problems require new language features as solutions. (Not to mention that new language features always causes new problems.)

In those days the Consumer interface was called Block.

I think this corresponds with JB Nizet's answer suggested by Marko above.

Later Brian explains why this was designed this way (the reason of problem)

Yes, you'd have to provide your own exceptional SAMs. But then lambda conversion would work fine with them.

The EG discussed additional language and library support for this problem, and in the end felt that this was a bad cost/benefit tradeoff.

Library-based solutions cause a 2x explosion in SAM types (exceptional vs not), which interact badly with existing combinatorial explosions for primitive specialization.

The available language-based solutions were losers from a complexity/value tradeoff. Though there are some alternative solutions we are going to continue to explore -- though clearly not for 8 and probably not for 9 either.

In the meantime, you have the tools to do what you want. I get that you prefer we provide that last mile for you (and, secondarily, your request is really a thinly-veiled request for "why don't you just give up on checked exceptions already"), but I think the current state lets you get your job done.

Supplier's declaration - Finnish Customs, However, suppliers' declarations in trade with some partner countries of the European Union are possible in the following cases: • Cross-border suppliers'� Supplier Declarations. When calculating preferences, you are legally obliged to provide complete proof of preferential origin in the form of vendor declarations for goods and many processing rules. Single and long-term supplier declarations can be entered and managed in Advantage Preference.


Edit

As pointed many times, you don't need any custom class, use Callable and Runnable instead

Wrong, outdated solution

Consider this generic solution:

// We need to describe supplier which can throw exceptions
@FunctionalInterface
public interface ThrowingSupplier<T> {
    T get() throws Exception;
}

// Now, wrapper
private <T> T callMethod(ThrowingSupplier<T> supplier) {
    try {
        return supplier.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
        return null;
}

// And usage example
String methodThrowsException(String a, String b, String c) throws Exception {
    // do something
}

String result = callMethod(() -> methodThrowsException(x, y, z));

[PDF] guidance on supplier's declaration, Only possible for goods receptors within the EU. Is generally a requirement for the issue of a supplier declaration of goods with preferential� Only possible for goods receptors within the EU. Is generally a requirement for the issue of a supplier declaration of goods with preferential originating status. Template of a long-term supplier declaration within the EU without origins (PDF) A long-term supplier declaration must contain the following elements: Information about the delivered


Since I have an additional point to make on this subject, I have decided to add my answer.

You have the choice to write a convenience method which either:

  1. wraps a checked-exception-throwing lambda into an unchecked one;
  2. simply calls the lambda, unchecking the exception.

With the first approach, you need one convenience method per functional method signature, whereas with the second approach, you need a total of two methods (except for primitive-returning methods):

static <T> T uncheckCall(Callable<T> callable) {
  try { return callable.call(); }
  catch (Exception e) { return sneakyThrow(e); }
}
 static void uncheckRun(RunnableExc r) {
  try { r.run(); } catch (Exception e) { sneakyThrow(e); }
}
interface RunnableExc { void run() throws Exception; }

This allows you to insert a call to one of these methods passing in a nullary lambda, but one which is closing over any arguments of the outside lambda, which you are passing to your original method. This way you get to leverage the automatic lambda conversion language feature without boilerplate.

For example, you can write

stream.forEachOrdered(o -> uncheckRun(() -> out.write(o)));

compared to

stream.forEachOrdered(uncheckWrapOneArg(o -> out.write(o)));

I have also found that overloading the wrapping method name for all lambda signatures often leads to ambiguous lambda expression errors. So you need longer distinct names, resulting in ever longer code char-for-char than with the above approach.

In the end, note that the said approach still doesn't preclude writing simple wrapper methods which reuse uncheckedRun/Call, but I found it simply uninteresting because the savings are negligible at best.

Long-term supplier declaration:what you need to know, commitment to the principles in this Supplier Declaration by the signature of authorised personnel. AKBM's safe and secure work environment which as a. Important: ISF Filer must ask, request, and/or demand this Bill of Lading number from there vendor, supplier, or oversea seller. Important: The Bill of Lading number can either be the Master Bill of Lading (MBL) number or House Bill of Lading (HBL) number, either B/L number is acceptable for ISF filing. Is This Full Container:


I added my own solution, not neccessarilly a direct answer to my question, which introduces the following after some revisions:

@FunctionalInterface
public interface CheckedSupplier<T, E extends Exception> {
    public T get() throws E;
}

private <R> R getFromConfig(final String entryKey, final Function<String, R> converter) throws IOException {
    Objects.requireNonNull(entryKey);
    Objects.requireNonNull(converter);
    configLastModified = Files.getLastModifiedTime(configFile);
    return ConfigFileUtils.readFileEntry(configFile, entryKey, converter);
}

private <T> T handleIOException(final CheckedSupplier<T, IOException> supplier) {
    Objects.requireNonNull(supplier);
    try {
        return supplier.get();
    } catch (IOException ex) {
        throw new IllegalStateException("The config file (\"" + configFile + "\") has not been found.");
    }
}

This were all one-time only declarations, now I add two variants of the calling code:

private Duration durationFromConfig() {
    return handleIOException(() -> getFromConfig(subClass.getSimpleName(), Duration::of));
}

private int threadsFromConfig() {
    return handleIOException(() -> getFromConfig(subClass.getSimpleName() + "Threads", Integer::parseInt));
}

I am not too happy about converting an IOException to an UncheckedIOException, as:

  1. I would need to add an unchecked variant of every method that can throw an IOException.
  2. I prefer obvious handling of the IOException, instead of relying on hoping that you do not forget to catch the UncheckedIOException.

[PDF] SUPPLIER DECLARATION Compliance with Laws , With a battery system you can store electricity to use later or sell back to your supplier – either way making savings. But battery systems cost at least £4,000, so it will mean even longer


possible cash influx resulting from transfer of assets to the new provider; Variable pricing: The customer pays a fixed price at the low end of a supplier’s provided service,


Equipment and Supplies for Business Use . First, note that these purchases are for business purposes only, not for personal use. If you buy business equipment, such as a computer, it must be used entirely for your business in order for you to deduct the full cost as a business expense.


“In a land far to the east, there exists a strange store that has rejected a three Michelin star rating multiple times. The prices are expensive. A combo set of soup and egg fried rice costs 288 RMB. Oh, I forgot it also includes a side dish of pickles. Even so, very many people lineContinue Reading →