Reputation: 2884
I'm just wondering why the compiler gives me this error. The try block will be executed every time the function is called and that means the variable will get assigned. But still it doesn't let me compile.
using System;
namespace Checking
{
class Program
{
static void Main(string[] args)
{
int intNum;
intNum = readValue("Please enter a number: ");
}
static int readValue(string strPrompt)
{
int intRes;
Console.WriteLine(strPrompt);
try
{
intRes = Convert.ToInt32(Console.ReadLine()); // Gets assigned here! But still doesnt allow me to compile!
}
catch (Exception ex)
{
Console.WriteLine("Please enter a numeric value.\n");
readValue(strPrompt);
}
return intRes;
}
}
}
Putting return intRes inside the try block allows me to get rid of that error, but then an error crops up saying not all code paths return a value. I understand the errors, but I still don't understand why it won't allow me to compile, the try block gets executed every time right?
I also know that assigning 0 to intRes will get rid of that error.
Regards,
Upvotes: 0
Views: 1516
Reputation: 700152
The compiler is right. The variable is not always assigned.
If the conversion fails, the assignment never happens, and the execution continues inside the catch block, where you call the function again, but you have forgotten to assign the return value of that call to the variable:
catch (Exception ex)
{
Console.WriteLine("Please enter a numeric value.\n");
intRes = readValue(strPrompt);
}
Here's an anternative implementation using a while
and TryParse
:
static int readValue(string strPrompt) {
int intRes = 0;
bool done = false;
while (!done) {
Console.WriteLine(strPrompt);
if (Int32.TryParse(Console.ReadLine(), out intRes) {
done = true;
} else {
Console.WriteLine("Please enter a numeric value.\n");
}
}
return intRes;
}
Upvotes: 3
Reputation: 216243
The compiler has no way to know if your code inside the try block will throw an exception or not.
So, in case your code throws an exception, then the intRes variable will never be assigned.
Consequently the compiler emits the error message.
Also, as it stands, your code has a problem. You try to recursively call readValue inside the catch block to get a correct value but when your user finally enter a correct value, the main will never receive the value entered because you are using a local variable for the result value.
Upvotes: 1
Reputation: 51494
Because if the try fails, intRes has no value
In your catch use
intRes = readValue(strPrompt);
Initialise it with
int intRes = 0;
instead of
int intRes;
You may also want to look at the int.TryParse
syntax
Upvotes: 3
Reputation: 9538
You will get an uninitialized intRes
if Console.ReadLine()
throws an exception. That is why your compiler is complaining.
Upvotes: 2
Reputation: 498904
If Convert.ToInt32
failes, intRes
never gets assigned to.
Either set a default value when creating the variable, or assign to in the catch
block.
Upvotes: 3