For a long time I thought that it allows me to free up all the resources in the finally
block and I thought that if an exception happens in the try
block, then the resources will still be free up in the finally
block. But that seems not to be the case.
I have the following piece of code:
using System;
public sealed class Program
{
public static void Main()
{
try {
int zero = 0;
int i = 1/zero;
} finally {
Console.WriteLine("divide by zero"); //the line is never called
}
}
}
I never reach the line which prints to the console. That means that I will not be able to free up resource in finally
block in this case on the exception being thrown inside the try
block.
So, I believe there are two things: either I am missing something or the try
+ finally
combination has no use cases in the C#. The second statement makes sense, because I will get the same functionality as is produced by the above code with the code below:
using System;
public sealed class Program
{
public static void Main()
{
int zero = 0;
int i = 1/zero;
Console.WriteLine("divide by zero"); //the line is never called
}
}
But I am afraid that I might be missing something here. So, could someone confirm that the combination is useless or prove that it is not, please?
UPDATE
After the comment which is able to call the finally
block in its fiddle, I checked once more in the VS Code, and still I see no output.