TrueEddie
TrueEddie

Reputation: 2233

How C# Using Statement Translates to Try-Finally

I'm trying to wrap my head around this. According to this page on Using statements:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

But on this page about Try-Finally blocks it states:

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered.

So how can a Using statement be guaranteed to call the Dispose method in the event of an exception if it translates to a Try-Finally that is not guaranteed to call the finally statement?

Upvotes: 5

Views: 1115

Answers (3)

Matt Clark
Matt Clark

Reputation: 1171

If the exception unwind only ends with an unhandled exception that crashes the program then finally blocks do not run as execution ceases.

tl;dr Finally blocks are only run on success or on handled exception.

Upvotes: 0

Habib
Habib

Reputation: 223267

There are exceptions from which a program can't recover, in that case finally block will not execute. For example Stack overflow exception or Out of memory exception.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500585

It really does behave like a try/finally - so if the application terminates, the resource may not be disposed... and that's usually okay, because normally disposal is for releasing resources held by the process... and the OS will tidy those up anyway on process death. (That's not to say the Dispose method won't be called... it's just the same as with a normal try/finally.)

Obviously if you've got a "lock file" on the file system or something like that, that would be a problem - but you'd have the same problem in the face of a power cut etc.

Upvotes: 10

Related Questions