使用内部检查异常抛出运行时异常是不好的做法吗?

Jos*_*lds 6 java exception

这是不好的做法吗?

public String foo(File file) {
    StringBuilder sb = new StringBuilder();
    try(
            BufferedInputStream bis =
                    new BufferedInputStream(
                            new FileInputStream(file))
    ) {
        for(int c = bis.read(); c != -1; c = bis.read())
            sb.append((char) c);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)

假设没有办法从已检查的异常中优雅地恢复.

das*_*ght 5

这并不理想,但有些情况下没有其他解决方法.

foo(File file)接口方法的实现或超类方法的覆盖(未声明已检查的异常)时,此方法变得方便.这种情况会强制您在内部处理异常,或将其包装在未经检查的异常中.

然而,问题在于,子类RuntimeException应该表示编程错误; IOException另一方面,它表示编程错误,因此将其包装RuntimeException以绕过Java编译器的检查是错误的.