When a statement to a DB returns null, I am catching it this way:
private int GetLastRoundNumber(int period)
{
int id;
try
{
using (NpgsqlConnection con = new NpgsqlConnection(_entwConnection))
{
con.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT roundNumberId FROM race.folders WHERE period = @period ORDER BY roundNumberId DESC LIMIT 1;";
cmd.Parameters.AddWithValue("period", period);
return id = (int)cmd.ExecuteScalar();
}
}
}
catch (NullReferenceException e)
{
Debug.Write(e.Message);
Debug.WriteLine("Because of a new period, started with 1 again. Period: " + period + ".");
return id = 1;
}
}
So to this codepart my questions:
- Is it okay to have the try/catch block outside the using statement block?
- Is there a better way to handle the exception?
- Do I need to hit the catch block?
I am asking because as I learned it by now, for me it isn't a real exception, because when a new period starts, there is no Id inside.
Is this the correct way to deal with it?