Sobes.tech
Junior — Middle

Can you give an example where a finally block is used in code to handle completion of operations?

sobes.tech AI

Answer from AI

The finally block in Java is used to execute code that must run regardless of whether an exception was thrown or not after the try block. It is commonly used for resource cleanup, such as closing files, network connections, or streams.

Example:

FileInputStream fis = null;
try {
    fis = new FileInputStream("file.txt");
    // read data from the file
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close(); // ensure the file is closed
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, finally guarantees that the file will be closed even if an exception occurs during reading.