When I do the following, I get a warning that not all code paths return a value if the catch block doesn't return an int
; when that catch block returns an int, the capturedException test for null becomes unreachable unless it is placed inside a finally
block. Is putting the throw inside finally{} acceptable? Is the connection closed automatically as it would be in a synchronous method that employs the using
syntax?
public async Task<int> Write2Log()
{
ExceptionDispatchInfo capturedException = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
try
{
await cmd.Connection.OpenAsync();
return await cmd.ExecuteNonQueryAsync();
}
catch (Exception ex)
{
capturedException=ExceptionDispatchInfo(ex);
return -1;
}
// unreachable unless placed inside `finally` block
if (capturedException != null)
{
capturedException.Throw();
}
}
}
}