nerdexam
Oracle

1Z0-809 · Question #189

Given the content of the employee.txt file: Every worker is a master. Given that the employee.txt file is accessible and the file allEmp.txt does NOT exist, and the code fragment: try { List<String>…

The correct answer is A. Exception 1. Option A is correct because Files.write() is called with only StandardOpenOption.APPEND - this overrides the default options (CREATE, TRUNCATE_EXISTING, WRITE), meaning the file is not created if it doesn't exist. Since allEmp.txt is absent, a NoSuchFileException (a subclass of…

Question

Given the content of the employee.txt file: Every worker is a master. Given that the employee.txt file is accessible and the file allEmp.txt does NOT exist, and the code fragment: try { List<String> content = Files.readAllLines(Paths.get("employee.txt")); content.stream().forEach(line -> { try { Files.write( Paths.get("allEmp.txt"), line.getBytes(), StandardOpenOption.APPEND ); } catch (IOException e) { System.out.println("Exception 1"); } }); } catch (IOException e) { System.out.println("Exception 2"); } What is the result?

Options

  • AException 1
  • BException 2
  • CThe program executes, does NOT affect the system, and produces NO output.
  • DallEmp.txt is created and the content of employee.txt is copied to it.

How the community answered

(16 responses)
  • A
    75% (12)
  • B
    13% (2)
  • C
    6% (1)
  • D
    6% (1)

Explanation

Option A is correct because Files.write() is called with only StandardOpenOption.APPEND - this overrides the default options (CREATE, TRUNCATE_EXISTING, WRITE), meaning the file is not created if it doesn't exist. Since allEmp.txt is absent, a NoSuchFileException (a subclass of IOException) is thrown inside the lambda, which is caught by the inner catch block, printing "Exception 1".

Why the distractors are wrong:

  • B is wrong because the inner catch (IOException e) intercepts the exception before it can bubble up to the outer catch - "Exception 2" is never reached.
  • C is wrong because output is produced; the exception is caught and handled, it just doesn't crash the program.
  • D is wrong because APPEND alone does not imply file creation - you'd need to also pass StandardOpenOption.CREATE (or use the default options with no explicit options) to create a missing file.

Memory tip: Think of StandardOpenOption.APPEND as a strict "add to what's already there" flag - if there's nothing there yet, it refuses to work. To safely append-or-create, always pair it with StandardOpenOption.CREATE: APPEND + CREATE = safe; APPEND alone = danger if the file is missing.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice