所以我试图重构以下代码:
/**
* 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) 我有一个集成测试,其中一个我调用的方法有时会抛出异常.我想忽略异常,但我想以最优雅的方式做到这一点.
最初我这样做是这样的:
// 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) 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下有一些方法可以做到这一点吗?