重新投掷RuntimeExceptions

时间:2018-06-08 12:58:25

标签: exception

在我的代码中,我通常会重新抛出围绕RuntimeException的已检查异常。当我无法对异常做很多事情时,我会这样做,但我也不希望在我的方法签名中添加抛出。

所以我最终要做的是:

try {
  // code that may throw exception
}
catch (Exception e) {
  throw new RuntimeException(e)
}

这太冗长,降低了可读性。 我试着编写一个这样的辅助方法:

  public void ignoreException(Runnable runnable) {
    try {
      runnable.run();
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

然后这样称呼它:

  public static void main() {
    ignoreExcceptions(() -> Thread.sleep(1000));
  }

但它(当然)不会绕过编译器的异常检查。

有没有办法以更简洁,更易读的方式包装东西?

1 个答案:

答案 0 :(得分:0)

这是我解决此问题的方法:

public interface NonReturningCallable {

  public void call() throws Exception;

}

import java.util.concurrent.Callable;

public class ExceptionUtils {

  public static void checkExceptions(NonReturningCallable callable) {
    try {
      callable.call();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static <V> V checkExceptions(Callable<V> callable) {
    try {
      return callable.call();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

public class Test {
  public static void main(String[] args) {
    ExceptionUtils.checkExceptions(() -> Thread.sleep(1000));
    int a = ExceptionUtils.checkExceptions(() -> Math.min(1, 2));
  }
}

不幸的是,我不得不声明自己的NonReturningCallable接口,因为在JDK库中找不到该接口。