Unreachable code, but reachable with an exception

前端 未结 9 1695
说谎
说谎 2020-12-28 11:22

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 succes

9条回答
  •  自闭症患者
    2020-12-28 11:54

    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();
    }
    

提交回复
热议问题