如果在打开资源后引发了运行时异常-程序关闭了该资源?

问题描述 投票:0回答:1

我编写了一个简单的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;
}

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

感谢您的帮助

java exception runtimeexception
1个回答
0
投票

无论是否处理异常,总是执行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 docs Refer here

您可以通过尝试使用资源来关闭资源

try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
    // exception handling
}
// resources are closed as soon as try-catch block is executed.
© www.soinside.com 2019 - 2024. All rights reserved.