What is the best way to mark code unreachable, so the compiler won't give an error message? A short example:
int x;
if (y == 0) x = 1;
else if (y == 1) x = 2;
Console.WriteLine(x);
I know that y can be 0 or 1, but C# will give a message that x desn't get all path a value. The real code is not this, but I wanted to keep it shorter.
Is throwing an exception a good practice, or is there other method?
int x;
if (y == 0) x = 1;
else if (y == 1) x = 2;
else throw new Exception();
Console.WriteLine(x);
I would go with throwing an exception - it indicates that the world is not in a state you expect, and you'd be better off quitting before you do any damage:
if (y == 0)
{
x = 1;
}
else if (y == 1)
{
x = 2;
}
else
{
throw new IllegalStateException("y should be 0 or 1");
}
Alternatively, for simple situations like this, use a switch/case:
switch (y)
{
case 0:
x = 1;
break;
case 1:
x = 2;
break;
default:
throw new IllegalStateException("y should be 0 or 1");
}
(As noted in comments, if y
is a method parameter, then ArgumentOutOfRangeException
would be more appropriate. Or if y
is only not-one-or-zero because of a parameter value, then again, indicate that cause. The above is appropriate if basically it's a matter of the overall state of the world being broken.)
See more on this question at Stackoverflow