When the exception is thrown, the stack will unwind (execution will move out of the function) without returning a value, and any catch block in the stack frames above the function will catch the exception instead.
Hence, return false
will never execute.
Try manually throwing an exception to understand the control flow:
try {
command.CommandText = sb.ToString();
returnValue = command.ExecuteNonQuery();
// Try this.
throw new Exception("See where this goes.");
return returnValue == 1;
} finally {
command.Dispose();
}
manpreet
Best Answer
2 years ago
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 anInvalidOperationException
when "a method call is invalid for the object's current state". Therefore, if that would happen, execution of thetry
block would stop, thefinally
block would be executed, then would execute thereturn 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.What is my error of understanding here?