QuestionQ6

VerifiedSecure Coding Practices for Error Handling

James is a Java developer working at INFR INC. He has written Java code that opens a file, reads it line by line, and displays its contents in the text editor. He wants to ensure that any unhandled exception raised by the code automatically closes the opened file stream. Which exception-handling block should he use for this purpose?

Explanation

A try-with-resources statement automatically closes each declared resource when the block ends, including when an exception occurs. File streams implement Closeable/AutoCloseable, so they are closed without requiring explicit cleanup code in a finally block.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!