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?
c is called the source file which keeps the code of the program. Now, when we compile the file, the C compiler looks for errors. If the C compiler reports no error, then it stores the file as a . obj file of the same name, called the object file.
C Introduction C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
The origin of C is closely tied to the development of the Unix operating system, originally implemented in assembly language on a PDP-7 by Dennis Ritchie and Ken Thompson, incorporating several ideas from colleagues. Eventually, they decided to port the operating system to a PDP-11.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With