Java“尝试没有捕获”和“抓住没有尝试”

时间:2017-04-16 19:13:44

标签: java exception compiler-errors try-catch

我正在编写一个Java文件,但是当我尝试编译它时,我不断收到3条错误消息:

reader.java:35:错误:'尝试'没有'catch','finally'或资源声明         尝试

reader.java:48:错误:'抓住'没有'尝试'         catch(IOException e)

reader.java:52:错误:'抓住'没有'尝试'         catch(例外e)

3个错误

为什么呢?我错过了什么?这是我的代码:

public static void processRecords(String filenameIn, Person[] personArray)
{
    try 
    {
        FileReader fr = new FileReader(filenameIn);
        BufferedReader reader = new BufferedReader(fr);
        reader.readLine();

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

2 个答案:

答案 0 :(得分:3)

您无法将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();
    }
}

答案 1 :(得分:0)

您还可以使用try-with-resources完全取消reader.close()调用。

尝试(FileReader fr = new FileReader(filenameIn)){ ... }