-4

I am writing a Java file, but when I try to compile it I keep getting 3 error messages:

reader.java:35: error: 'try' without 'catch', 'finally' or resource declarations try

reader.java:48: error: 'catch' without 'try' catch(IOException e)

reader.java:52: error: 'catch' without 'try' catch(Exception e)

3 errors

Why? What am I missing? Here is my code:

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());
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
Jon Doe
  • 37
  • 2
  • 2
  • 8

2 Answers2

5

You can't put reader.close() between the try and the catch. Either put it in a finally block, or use a try-with-resources. Like,

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());
}

or with the finally block,

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();
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You can also eliminate the reader.close() call altogether by using try-with-resources.

try (FileReader fr = new FileReader(filenameIn)) { ... }