CAD
CAD

Reputation: 4302

Exception handling in DAL

In a MVP winforms application I'm handling exceptions as follows in DAL.

Since the user messaging is not a responsibility of DAL, I want to move it in to my Presentation class.

Could you show me a standard way to do that?

    public bool InsertAccount(IBankAccount ba)
    {
        string selectStatement = @"IF NOT EXISTS (SELECT ac_no FROM BankAccount WHERE ac_no=@ac_no) BEGIN INSERT INTO BankAccount ...";

        using (SqlConnection sqlConnection = new SqlConnection(db.ConnectionString))
        {
            using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
            {
                try
                {
                    sqlConnection.Open();
                    sqlCommand.Parameters.Add("@ac_no", SqlDbType.Char).Value = ba.AccountNumber;
                    //
                    //

                    sqlCommand.ExecuteNonQuery();
                    return true;
                }
                catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }
                if (sqlConnection.State == System.Data.ConnectionState.Open) sqlConnection.Close();
                return false;
            }

        }
    }

EDIT2 :

So based on the answers I re edited the post and now my exception handling code looks like this...

DAL

public bool InsertAccount(IBankAccount ba)
{
    try
    {
        sqlConnection.Open();
        //   
    }
    catch (SqlException)
    {
        throw new Exception("DataBase related Exception occurred");
    }
    catch (Exception)
    {
        throw new Exception("Exception occurred");
    }
}

BankAccountPresenter

    private void SaveBankAccount()
    {
        try
        {
           _DataService.InsertAccount(_model);
        }
        catch (Exception e) { MessagingService.ShowErrorMessage(e.Message); }
    }

Why I've caught exceptions in DAL is that even at the moment I'm not logging errors, I may have to do it in future.

And also this way I can differentiate the error massages in DAL, whether it's sql related or general.

I've used messaging service in my presenter when showing error messages.

Does this meaning full? Can this be simplified?

Upvotes: 1

Views: 2623

Answers (1)

Nathan
Nathan

Reputation: 6531

You're returning false to indicate that there has been an exception. This is not recommended.

Rethrow it

catch(Exception e) {
  //blah, maybe add some useful text to e
   throw;
}
finally { //close up shop Although, look up what using does first incidentally }

Then deal with it (catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }) in a higher level.

Reponse to EDIT2:

That's fine. However, your current implementation throws the 'actual' exception and its stack trace in the bin in favour of your helpful message. You need to add it as an inner exception like this:

catch(Exception e){    
     throw new Exception("some helpful message", e);
}

Upvotes: 5

Related Questions