Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I do when I am forced to write unreachable code?

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.

like image 349
Bosak Avatar asked Jun 06 '13 15:06

Bosak


1 Answers

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.

like image 83
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet