Cleanup code in Finally block - Csharp.Net
Q. Why should you write the cleanup code in Finally block?- Published on 31 Aug 15a. Compiler throws an error if you close the connection in try block.
b. Resource cannot be destroyed in catch block.
c. Finally blocks run whether or not exception occurs.
d. All of the above
ANSWER: Finally blocks run whether or not exception occurs.
The finally block always executes whether exception occurs or not. Finally block run when control leaves a try statement. You can write all cleanup code in finally block.
Example:
class Program
{
staticint a = 10, b = 0, c;
static void Main(string[] args)
{
try
{
c = a / b;
}
finally
{
Console.WriteLine(c);
}
}
}