I'm trying to use Suppliers#memorize
on a function that throws IOException
Snippet:
private Supplier<Map> m_config = Suppliers.memoize(this:toConfiguration);
This gives an exception: Unhandled exception type IOException
so I had to do something like this:
public ClassConstructor() throws IOException
{
m_config = Suppliers.memoize(() -> {
try
{
return toConfiguration(getInputFileName()));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
});
if(m_Configuration == null) {
throw new IOException("Failed to handle configuration");
}
}
I would like the CTOR to forward the IOException
to the caller.
The proposed solution is not so clean, is there a better way to handle this situation?
UncheckedIOException
You're tagging java-8, so you should use the UncheckedIOException
which is present for this very use case.
/**
* @throws java.io.UncheckedIOException if an IOException occurred.
*/
Configuration toConfiguration(String fileName) {
try {
// read configuration
} catch (IOException e) {
throw new java.io.UncheckedIOException(e);
}
}
Then, you can write:
m_config = Suppliers.memoize(() -> toConfiguration(getInputFileName()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With