Skip to content

finally and using

Question

How can you ensure that certain code is always called, regardless of an exception being thrown?

Short interview answer

Use finally for cleanup that must run when a try block exits. Prefer using or await using for IDisposable or IAsyncDisposable resources 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.

Sources