
What
is the purpose of finally block
|
For example,
your code might use unmanaged resources. If there is any exception occurrence
and your program is going to terminate then before terminating it is essential
to release all unmanaged resources. Where do you do it? You can write
such critical section of code inside finally block. Code inside finally
block will be executed at all times irrespective of exceptions.
This is demonstrated using the example shown below:
public class
sampleClass {
public static void Main() {
StreamReader sampleReader = new StreamReader(sample.txt);
try {
sampleReader = new StreamReader(sample.txt);
string sampleStr;
while ((sampleStr = sampleReader.ReadLine()) != null) {
Console.WriteLine(sampleStr);
}
}
catch(Exception exp) {
Console.WriteLine(Exception Occurred:+exp);
}
finally {
if (sampleReader != null) {
sampleReader.Close();
}
}
}
}
In the above example, you read the contents of file sample.txt inside try block. If there are any error occurrences like OutofMemoryException then catch block will execute. In normal cases, the program will terminate. Since you have included finally block, the code inside finally block will execute even if an exception is caught and therefore the sampleReader will get closed irrespective of exception occurrences.
_______________________________________________________________________
FREE Subscription
Subscribe
to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.
Note
: We never rent, trade, or sell my email lists to
anyone.
We assure that your privacy is respected
and protected.
Visit .NET Programming Tutorial Homepage
______________________________________________________