【问题标题】:If a runtime exception was thrown after a resource was open - the program close the resource?如果在打开资源后引发运行时异常 - 程序关闭资源?
【发布时间】:2020-03-21 12:20:45
【问题描述】:

我写了一个简单的 java 函数,它读取一个浮点值文件,如果文件没有找到或 正在读取的值不是浮点数,程序抛出异常。

我的问题是程序打开文件但值的格式不是浮点的情况 - 程序可以关闭资源吗?还是我应该考虑可能发生的运行时异常?

 public static ArrayList<Double> readValues(String filename) throws 
    FileNotFoundException {

    var file = new File(filename);

    var fileScanner = new Scanner(file);
    var doubleList = new ArrayList<Double>();


    //In case the values are not of double type and the scanner 

        while(fileScanner.hasNext()) 
            doubleList.add( Double.parseDouble( fileScanner.next() ) );


    fileScanner.close();
    return doubleList;
}

好的,我更新了要在“finally”语句中使用的代码

    public static ArrayList<Double> readValues(String filename) throws 
    FileNotFoundException {

    var file = new File(filename);

    var fileScanner = new Scanner(file);
    var doubleList = new ArrayList<Double>();


    //In case the values are not of double type and the scanner 
    try {
        while(fileScanner.hasNext()) 
            doubleList.add( Double.parseDouble( fileScanner.next() ) );
    }finally {
        fileScanner.close();
    }

    return doubleList;
}

如果有更好的想法,我想知道。

感谢您的帮助

【问题讨论】:

  • 在try-finally的try-catch-finally的finally块中关闭资源,因为不管是否抛出异常,finally块总是在try块之后执行
  • 好的,但如果我使用第一个程序(示例)。这是一个错误吗?或者默认情况下我们不应该考虑运行时异常?谢谢!
  • 默认情况下,我们应该考虑运行时异常,在你的第一个代码中你会抛出 FileNotFoundException,如果发生 NumberFormatException,它不会被捕获并且无法抛出,所以程序会以异常停止。跨度>
  • 当程序关闭时,它会释放它持有的所有资源。因此,如果您的程序在无法读取文件时关闭,它也会关闭文件。所以第一个例子是好的。但是,您最好自己处理资源。

标签: java exception runtimeexception


【解决方案1】:

无论是否处理异常,Java finally 块总是被执行。

Please refer to this 一个标准的方法

FileInputStream fileInputStream = null;
try {
    fileInputStream = new FileInputStream(...);
    // do something with the inputstream
} catch (IOException e) {
    // handle an exception
} finally { //  finally blocks are guaranteed to be executed
    // close() can throw an IOException too, so we got to wrap that too
    try {
        if (fileInputStream != null) {
            fileInputStream.close();
        }        
    } catch (IOException e) {
        // handle an exception, or often we just ignore it
    }
}

来自 java7:try-with-resources 语句

来自 oracle 文档Refer here

你可以通过 try with resources 来关闭资源

try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
    // exception handling
}
// resources are closed as soon as try-catch block is executed.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多