A developer is writing a method that reads a file and processes its content. The method must ensure that if an IOException occurs during reading, the method throws a custom ApplicationException that wraps the original IOException, and that any resources opened are closed properly. Which approach correctly implements this requirement?
Trap 1: try { ..
Does not rethrow the exception; it only prints it.
Trap 2: catch (Exception e) { throw new ApplicationException(e); } finally…
Catches Exception too broadly, not specific to IOException.
Trap 3: try { ..
Resource may not be closed if an exception occurs before close().
- A
try { ... } catch (IOException e) { System.err.println(e); } finally { reader.close(); }
Why wrong: Does not rethrow the exception; it only prints it.
- B
catch (Exception e) { throw new ApplicationException(e); } finally { reader.close(); }
Why wrong: Catches Exception too broadly, not specific to IOException.
- C
try (BufferedReader reader = Files.newBufferedReader(path)) { ... } catch (IOException e) { throw new ApplicationException(e); }
Uses try-with-resources for automatic closure and wraps only IOException.
- D
try { ... reader.close(); } catch (IOException e) { throw new ApplicationException(e); }
Why wrong: Resource may not be closed if an exception occurs before close().