I’m having a problem understanding the order of execution for the try-catch-finally. All the example I’ve seen (like in:http://stackoverflow.com/questions/4191027/order-of-execution-of-try-catch-and-finally-block) have a very simple “catch” part which print to console. but what happen if I use a “throw” statement in the catch?
The simplest code I could think of which capture the problem:
public class TestClass
{
void Foo(int num)
{
int answer = 100;
try
{
answer = 100 / num;
}
catch (Exception e)
{
//Probably num is 0
answer = 200;
throw;
}
finally
{
Console.WriteLine("The answer is: " + answer);
}
}
}
If num == 2, then the output will be:
The answer is: 50
But what would be printed for num == 0?
The answer is: 100
The answer is: 200
No printing at all…
or is it just a “undefined behavior”?
The easiest way to test is to try it. It should print – the answer is 200, and then error out.
Finally will always be called (except for some exceptions that cannot be caught, e.g. stack overflow). You should take care to try and not throw an exception from within your finally block…
Here your flow will be: