I have this simple piece of code:
public static int GetInt(int number)
{
int[] ints = new int[]{ 3, 7, 9, int.MaxValue };
foreach (int i in ints)
if (number <= i)
return i;
return int.MaxValue; //this should be unreachable code since the last int is int.MaxValue and number <= int.MaxValue is allways true so the above code will allways return
}
The problem is that the compiler says that not every execution path returns a value. So I have to write code that will be never reached. My question is, what should I do in a situation like this? Should I return some default value or should I throw an exception. Also, if I want to throw an exception, what exception is suitable for throwing? I didn't find anything like UnreachableCodeException
.
I'd be tempted to use InvalidOperationException
- or some other exception which you wouldn't explicitly catch. Give it a message which indicates that you really didn't expect to get here. This is a "world is seriously broken" failure. InvalidOperationException
doesn't quite capture this, but I can't think of a better one offhand. You could always create your own exception to use throughout your codebase, of course.
Don't just return a value, as otherwise you'll never find out if your world is upside-down.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With