K
Ken
What is the purpose of a finally block in try-catch-
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still
execute since it comes after the whole thing.
So... what is the difference between a "finally" block and
nothing at all?
void foo()
{
int i = 123;
string s = "Some string";
object o = s;
try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLine("Exception!");
}
finally
{
Console.Write("i = {0}", i);
}
}
Now, consider something similar:
void foo()
{
int i = 123;
string s = "Some string";
object o = s;
try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLine("Exception!");
}
Console.Write("i = {0}", i);
}
finally? I am confused because, if I am reading the
definition correctly, this block seems unnecessary.
Consider the following from the Visual Studio
documentation. In the first foo(), the statement in the
finally block will execute even though there is an
exception in the try block. In the second foo(), I took
the statement out of the finally block but it should still
execute since it comes after the whole thing.
So... what is the difference between a "finally" block and
nothing at all?
void foo()
{
int i = 123;
string s = "Some string";
object o = s;
try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLine("Exception!");
}
finally
{
Console.Write("i = {0}", i);
}
}
Now, consider something similar:
void foo()
{
int i = 123;
string s = "Some string";
object o = s;
try
{
// Invalid conversion; o contains a string not an int
i = (int) o;
}
catch (Exception e)
{
Console.WriteLine("Exception!");
}
Console.Write("i = {0}", i);
}