如何在java中优雅地处理FileNotFoundexception

Kai*_*Kai 4 java exception

我正在尝试编写一个返回文件输入流的函数.它看起来像这样:

public FileInputStream getFileInputStream() {
    File file;
    try {
        file = new File("somepath");
    } catch (Exception e) {
    }
    FileInputStream fInputStream = new FileInputStream(file);
    return fInputStream;
}
Run Code Online (Sandbox Code Playgroud)

所以这是我的问题 - 显然在异常情况下不会创建文件.但我需要一个文件对象来实例化FileInputStream.我有点迷失在这里,如何在仍然返回有效的FileInputStream对象时处理异常?

Mar*_*aux 10

这是进一步抛出异常的想法.只是将异常抛给调用者.

public FileInputStream getFileInputStream() throws FileNotFoundException
{
    File file = new File("somepath");
    FileInputStream fInputStream = new FileInputStream(file);
    return fInputStream;
}
Run Code Online (Sandbox Code Playgroud)

这样,调用者必须处理它.这是使用它的最简洁方法.

备注:您应该知道实例化File对象永远不会抛出异常.它的实例化FileInputStream可能会抛出异常.

  • 我会抛出FileNotFoundException,因为不需要扩展类型. (3认同)