如何在方法抛出Checked-Exception时使用Suppliers.memoize

Shv*_*alb 4 java guava java-8

我正在尝试使用Suppliers#memorize抛出的函数IOException

片段:

private Supplier<Map> m_config = Suppliers.memoize(this:toConfiguration);
Run Code Online (Sandbox Code Playgroud)

这给出了一个异常:未处理的异常类型IOException

所以我不得不这样做:

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");
 }
}
Run Code Online (Sandbox Code Playgroud)

我希望CTOR将其转发IOException给来电者.建议的解决方案不是那么干净,有没有更好的方法来处理这种情况?

Oli*_*ire 6

使用 UncheckedIOException

你正在标记,所以你应该使用UncheckedIOException这个用例.

/**
 * @throws java.io.UncheckedIOException if an IOException occurred.
 */
Configuration toConfiguration(String fileName) {
  try {
    // read configuration
  } catch (IOException e) {
    throw new java.io.UncheckedIOException(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,你可以写:

m_config = Suppliers.memoize(() -> toConfiguration(getInputFileName()));
Run Code Online (Sandbox Code Playgroud)