Search code examples
c#.netlibrary-design

What would you do here? Return a null or throw an exception (framework design guides)


I'm developing a C# .NET Framework 4.0 library.

I have this code:

public static byte GetBatchStatus(string connString)
{
    if (string.IsNullOrEmpty(connString))
        throw new ArgumentNullException("connString");

    byte status;

    using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
    {
        conn.Open();

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = GetBatchStatusValueSQL;
        cmd.CommandType = CommandType.Text;
        cmd.Connection = conn;

        object o = cmd.ExecuteScalar();
        // Throws an ArgumentNullException if o is null.
        if (o == null)
            throw new ArgumentNullException("o");

        status = Convert.ToByte(o);
    }

    return status;
}

cmd.ExecuteScalar(); could return a null, but Convert.ToByte(o); returns 0.

If cmd.ExecuteScalar(); returns null its an error, because the value I'm looking for must be on database. If that value is not on database is an error.

What would you do here? Return a null or throw an exception?


Solution

  • If that value is not on database is an error.

    An error in terms of "my belief system about the state of the system has been violated" or "the input must be invalid somehow"? It sounds like it's more the former - so I'd throw an exception. It sounds like the caller can't reasonably continue in this case. If they can, that's a different matter.

    You might want to use InvalidOperationException, or perhaps create your own exception (InvalidDatabaseStateException for example) given that it's not really the state of this object which is invalid.