Unreachable code, but reachable with an exception

0xCAFEBABE picture 0xCAFEBABE · Mar 12, 2019 · Viewed 14.8k times · Source

This code is part of an application that reads from and writes to an ODBC connected database. It creates a record in the database and then checks if a record has been successfully created, then returning true.

My understanding of control flow is as follows:

command.ExecuteNonQuery() is documented to throw an Invalid​Operation​Exception when "a method call is invalid for the object's current state". Therefore, if that would happen, execution of the try block would stop, the finally block would be executed, then would execute the return false; at the bottom.

However, my IDE claims that the return false; is unreachable code. And it seems to be true, I can remove it and it compiles without any complaints. However, for me it looks as if there would be no return value for the code path where the mentioned exception is thrown.

private static bool createRecord(String table,
                                 IDictionary<String,String> data,
                                 System.Data.IDbConnection conn,
                                 OdbcTransaction trans) {

    [... some other code ...]

    int returnValue = 0;
    try {
        command.CommandText = sb.ToString();
        returnValue = command.ExecuteNonQuery();

        return returnValue == 1;
    } finally {
        command.Dispose();
    }

    return false;
}

What is my error of understanding here?

Answer

The General picture The General · Mar 12, 2019

Compiler Warning (level 2) CS0162

Unreachable code detected

The compiler detected code that will never be executed.

Which is just saying, the Compiler understands enough through Static Analysis that it cant be reached and completely omits it from the compiled IL (hence your warning)

Note : You can prove this fact to your self by trying to Step on to the Unreachable Code with the debugger, or using an IL Explorer