1. Learn
  2. /
  3. Courses
  4. /
  5. Data Types and Exceptions in Java

Connected

Exercise

Using finally in a real example

Finally blocks are generally used to close and clean up resources like a database or file that are being use - regardless of normal flow or whether an exception has occurred.

Here, you will simulate opening a file, writing text to the file, as well as closing the file - all with method calls. You use finally to close the simulated file regardless of whether an exception occurs.

Instructions

100 XP
  • Begin a try block around work that opens a file and writes to the file
  • Capture any exception that might occur in opening the simulated file and writing text to it.
  • Add a finally block to close the simulated file, which will get called if the program runs without issue or if an exception occurs when opening the file or writing to the file.