相关疑难解决方法(0)

是否可以声明供应商<T>需要抛出异常?

所以我试图重构以下代码:

/**
 * 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 …
Run Code Online (Sandbox Code Playgroud)

java java-8 functional-interface

22
推荐指数
4
解决办法
2万
查看次数

在Java8中寻找内置函数来忽略异常

我有一个集成测试,其中一个我调用的方法有时会抛出异常.我想忽略异常,但我想以最优雅的方式做到这一点.

最初我这样做是这样的:

// GIVEN
NewsPaper newspaper = new NewsPaper();
Coffee coffee = new Coffee();

// WHEN
try{
    coffee.spill()
}catch(Exception e){
    // Ignore this exception.  I don't care what coffee.spill 
    // does as long as it doesn't corrupt my newspaper
}

// THEN
Assert.assertTrue(newspaper.isReadable);
Run Code Online (Sandbox Code Playgroud)

在浏览stackoverflow时,我注意到在这个答案中我可以像这样重写我的代码:

// GIVEN
NewsPaper newspaper = new NewsPaper();
Coffee coffee = new Coffee();

// WHEN
ingoreExceptions(() -> coffee.spill());


// THEN
Assert.assertTrue(newspaper.isReadable);
Run Code Online (Sandbox Code Playgroud)

但是,我需要提供自己的{{ignoringExc}}实现:

public static void ingoreExceptions(RunnableExc r) {
  try { r.run(); } catch …
Run Code Online (Sandbox Code Playgroud)

java lambda exception java-8

3
推荐指数
1
解决办法
412
查看次数

具有true/false结果的Java一线异常处理

boolean pingOK = false;
try {
  pingOK = InetAddress.getByName(ip).isReachable(200);
} catch(IOException e) {
  pingOK = false;
}
Run Code Online (Sandbox Code Playgroud)

这些代码可以从6行减少到1行吗?

如:

boolean pingOK = withNoException(InetAddress.getByName(ip).isReachable(200));
Run Code Online (Sandbox Code Playgroud)

也许Java 8以上的一些功能异常技巧?

或者在Java 7下有一些方法可以做到这一点吗?

java syntax

1
推荐指数
1
解决办法
541
查看次数

标签 统计

java ×3

java-8 ×2

exception ×1

functional-interface ×1

lambda ×1

syntax ×1