Junior — Middle
What role does the finally block play in exception handling?
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 and any catch blocks. Typically, resource cleanup operations are placed in finally, such as closing files, database connections, or releasing other resources.
Example:
try {
// code that might throw an exception
} catch (Exception e) {
// exception handling
} finally {
// code that always executes
// for example, closing a file
}