java - Java “try without catch”和 “catch without tr

最佳答案

您不能将reader.close()放在trycatch之间。可以将其放在 finally block中,也可以使用 try-with-resources 。喜欢,

try (BufferedReader reader = new BufferedReader(new FileReader(filenameIn))) {
    reader.readLine();
    for (int i = 0; i < personArray.length; i++) {
        String[] data = reader.readLine().split("/t"); // <-- should be \\t for tab.
        personArray[i] = new Person(Integer.parseInt(data[0]), data[1], 
                data[2], Integer.parseInt(data[3]));
    }
} catch (IOException e) {
    System.out.println("ERROR: WRONG FILE " + e.toString());
} catch (Exception e) {
    System.out.println("ERROR" + e.toString());
}

或使用finally块,
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader(filenameIn));
    reader.readLine();
    for (int i = 0; i < personArray.length; i++) {
        String[] data = reader.readLine().split("\\t"); // <-- to split on tab.
        personArray[i] = new Person(Integer.parseInt(data[0]), 
                data[1], data[2], Integer.parseInt(data[3]));
    }
} catch (IOException e) {
    System.out.println("ERROR: WRONG FILE " + e.toString());
} catch (Exception e) {
    System.out.println("ERROR" + e.toString());
} finally {
    if (reader != null) {
        reader.close();
    }
}

关于java - Java “try without catch”和 “catch without try” ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441060/

上一篇:c++ - 为什么我看到 “member function with the same name as its class must be a constructor”?

下一篇:c++ - C++错误,编译器无法识别字符串::push_back [closed]

相关文章:

python - 在 try/except block 中创建变量是否被认为是一种不好的做法?

exception - 如何使用动态变量和中止控制在方案中定义异常?

java - 如何制作检查输入验证的 do-while 循环

java - 快速修复/J : Enable protocols and ciphersuite setting

java - 是否适合在 Java 中对从数据库检索的一小部分数据执行连接操作

java - 从 CalendarView 获取自 UNIX 纪元以来的毫秒时间

java - 将 super/this 构造函数调用中抛出的异常包装到其他异常中

c++ - 这是我第一次编程,我无法运行我的代码

haskell - 专门化未使用的类型变量时不可触及的类型

C++变量的多个定义

相关文章:

c++ - 长双二维动态数组C++

c++ - 以下代码段出了什么问题?

java - 为什么此代码段显示编译错误?

c++ - 无法使用std::pair and constructors [closed]编译代码

c++ - 声明和初始化struct类型变量时出错

c++ - 为什么我看到 “member function with the same name a

c++ - g++,如何找到出错的地方?

c# - 如果其他语句不起作用

c++ - "expected ';在返回语句之后,有人可以告诉我我的代码有什么问题吗?

objective-c - ARC 不允许将 'int' 隐式转换为 'id _Nonnull'