In the following code integers n1
and n2
can be accessible inside the try
block.
However they are not recognized by catch
and finally
block. May I know the reason?! There is ERROR if I try to print n1
and n2
values in catch
block and finally
block.
static void Main(string[] args)
{
int n1, n2;
try
{
n1 = Convert.ToInt32(Console.ReadLine());
n2 = Convert.ToInt32(Console.ReadLine());
int result;
result = n1 / n2;
Console.WriteLine("Result " + result);
}
catch (Exception ex)
{
Console.WriteLine("Error, please provide non zero value for denominator");
Console.WriteLine("n1 = {0} and n2 = {1}", n1, n2); -> why n1, n2 are unassigned local variables here.
Console.ReadLine();
}
finally
{
Console.ReadLine();
Console.WriteLine("n1 = {0} and n2 = {1}", n1, n2); -> why n1, n2 are unassigned local variables here.
}
}
However they are not recognized by catch and finally block. May I know the reason?!
Sure - they're not definitely assigned. Imagine Console.ReadLine
throws an exception. You catch that exception - but you haven't assigned a value to n1
or n2
.
You might want to provide initial values for them where you declare them - that way they'd always be definitely assigned. But it's not really clear what you want to happen or why you're trying to use them in the finally
block anyway. If you really want to access them after the finally
block, you could just return or rethrow the exception within the catch
block - that way, the only way of getting to after the finally
block would be via code that assigns values to n1
and n2
, so they'd be definitely assigned and you could read from them.
See more on this question at Stackoverflow