finally and using
Question
How can you ensure that certain code is always called, regardless of an exception being thrown?
Short interview answer
Use
finallyfor cleanup that must run when atryblock exits. Preferusingorawait usingforIDisposableorIAsyncDisposableresources because they generate the required disposal pattern.
Detailed answer
finally normally runs whether the try succeeds, returns, or throws, although process-terminating failures are exceptional cases:
var stream = File.OpenRead(path);
try { Process(stream); }
finally { stream.Dispose(); }
For a stream or database connection, using expresses the same ownership more clearly and disposes the resource even if the body throws. Do not throw a new exception from finally, because it can hide the original failure.