Search code examples
c#try-catch

My catch blocks are always the same. How can I stop repeating this?


I have countless methods that follow this exact pattern

using (var Connection = GetAndOpenSQLConnection())
{
   try
   {
        //Do SQL stuff, usually returning the results from a stored procedure.
   }
   catch (Exception Ex)
   {
      //Same catch every time.
      MessageBox.Show(Ex.ToString()); 
      return null;
   }
}

And I'm sick of the repetition. Is there any way to write these methods without having to repeat the same try/catch every time? The things inside the try might change, but the code around try never does. My first instinct is to turn to Actions and Funcs, but I'm under the (correct?) impression that they simply don't agree with try/catch and I don't particularly want to take risks with not closing connections when the using block is exited.


Solution

  • You say they are same, but what if you don't want to catch all exceptions there anymore, but only say a SqlException or one with a specific Number. Once you use that helper method you 'd have to live with that you catch all there. But for what it's worth, maybe this is helpful anyway:

    public static class Helper
    {
        public static TReturn SafeTryCatch<TReturn>(Func<TReturn> tryAction, Action<Exception> exceptionAction = null) where TReturn: class
        {
            try
            {
                return tryAction();
            }
            catch (Exception ex)
            {
              if(exceptionAction != null) exceptionAction(ex);
              return null;
            }
        }
    }
    

    You could use it for example in this way:

    void DoSomethingWithDatabase()
    {
        using var connection = GetAndOpenSQLConnection();
        List<DbResult> resultList = Helper.SafeTryCatch(
            () => GetDbResult(connection), ex => MessageBox.Show(ex.ToString())
        );
    }
    

    Here GetDbResult is a method that takes your connection and loads the data from DB:

    List<DbResult> GetDbResult(IDbConnection connection ){...}