Unreachable code, but reachable with an exception

前端 未结 9 1719
说谎
说谎 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 12:00

    It seems, you are looking for something like this:

    private static bool createRecord(string table,
                                     IDictionary data,
                                     System.Data.IDbConnection conn,
                                     OdbcTransaction trans) {
      [... some other code ...]
    
      // Using: do not call Dispose() explicitly, but wrap IDisposable into using
      using (var command = ...) {
        try {
          // Normal flow:
          command.CommandText = sb.ToString();
    
          // True if and only if exactly one record affected
          return command.ExecuteNonQuery() == 1;
        }
        catch (DbException) {
          // Exceptional flow (all database exceptions)
          return false;
        }
      }
    }
    

    Please, note, that finally doesn't swallow any exception

    finally {
      // This code will be executed; the exception will be efficently re-thrown
    }
    
    // And this code will never be reached
    

提交回复
热议问题