Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Suppliers.memoize when method throws Checked-Exception

Tags:

java

java-8

guava

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?

like image 846
Shvalb Avatar asked Mar 06 '23 21:03

Shvalb


1 Answers

Use 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()));
like image 143
Olivier Grégoire Avatar answered Apr 06 '23 09:04

Olivier Grégoire