Java OCA OCP Practice Question 3053

Question

Which one of the following code snippets shows the correct usage of try-with-resources statement?

a)  public static void main(String []files) {
        try (FileReader inputFile
                = new FileReader(new File(files[0]))) {
                    //...
        }//  w ww. j  av a2 s. co  m
        catch(IOException ioe) {}
    }

b)  public static void main(String []files) {
        try (FileReader inputFile
                = new FileReader(new File(files[0]))) {
                    //...
        }
        finally { }
        catch(IOException ioe) {}
    }

c)  public static void main(String []files) {
        try (FileReader inputFile
                = new FileReader(new File(files[0]))) {
                    //...
        }
        catch(IOException ioe) {}
        finally { inputFile.close(); }
    }

d)  public static void main(String []files) {
        try (FileReader inputFile
                = new FileReader(new File(files[0]))) {
                    //...
        }
    }


a)

Note

option b) provides finally before the catch block, it will result in a compiler error.

option c) uses the variable inputFile in the statement inputFile.close() that is not accessible in the finally block and hence results in a compiler error.

option d) the required catch block in this context is missing in the code (because the try block code may throw IOException), and hence it is incorrect usage.




PreviousNext

Related