What does the finally block guarantee, and when is it commonly used?
Short answer
Code in a finally block ALWAYS runs after the try (and any catch) block completes, whether an exception was thrown or not, and even if the try block contains a 'return' statement — making it the standard place for cleanup code like closing files or releasing resources.
Advertisement
AModel answer
Code in a finally block ALWAYS runs after the try (and any catch) block completes, whether an exception was thrown or not, and even if the try block contains a 'return' statement — making it the standard place for cleanup code like closing files or releasing resources.
FileStream? file = null;
try {
file = File.OpenRead("data.txt");
ProcessFile(file);
} finally {
file?.Dispose(); // always runs, ensuring the file handle is released
}Real-world example
Guaranteeing a database connection or file handle is properly closed regardless of whether the operation succeeded or threw.
Likely follow-ups
- How does the 'using' statement relate to and often replace a manual try/finally for disposal?
Related topics