views:

62

answers:

2

hi,

i have this application structure: 1. Presentation Layer which calls 2. Business Logic Layer which in turn calls 3. Data Access Layer to do the dealing with the database.

Now i have a Contacts page from where i can add a new contact to the database.

So to add a New Contact i fill in all the required details and then call a Add Method (residing in the BLL) from the page, which in turn call a Add Method residing in the DAL.

this method in the DAL returns the Current Identity of the record which is then return back to the BLL method and finally delivered on the page.

this is fine. but what if a get an exception how do i handle it properly because the method in DAL has a return type of int and i dont want to throw another error!! coz other wise i will have to write try catch in almost all the methods.

//something like this
public int AddMethod(ContactClass contactObj)
{
    int result = 0;

    try
    {
        result = ExecuteSomeSP("SPName", SP_Parameters);
    }
    catch(SQLException se)
    {
        throw new SQLException
    }

    return result;
}

rather i want to show the user a user-friendly message which they can easily understand and in the mean while i will send a mail to myself documenting the Error that just occurred.

Also kindly tell me how can i implement my custom exception classes.

Please tell me how do i do this!!

thank you.

+3  A: 

You shouldn't need a try/catch in every method. But you usually need a try/catch in every Layer (for a certain action).

And that is proper, each layer has to deal with its own broken contracts, cleanup etc.

The conversion from Exception to "friendly message" is something for the GUI, not a lower layer.

And when you catch and re-throw an exception, make sure you don't loose information, forward it in the InnerException property:

try
{
   // DAL
}
catch (DALException de)
{
   // Log, ....

   throw new BLLException(message, de);
}
Henk Holterman
@Henk - Corrected typo.
Petar Minchev
+1  A: 

Do not try catch in every method or layer, only were it is reasonable. A try catch should never act like a conditional. The presentation layer should never have logic in it.

Since your using a DAL interface I would create a custom DalException and throw that over the SQLException

public int addMethod(ContactClass contactObj) throws DalException {
    try {
        return ExecuteSomeSP("SPName", SP_Parameters);
    }
    catch(SQLException e) {
        throw new DalException(e);
    }
}

In your business logic layer catch the exception and produce the popup using the presentation layer

public void addMethod(ContactClass contactObj) {
    try {
        dal.addMethod(contactObj);
    }
    catch(DalException e) {
        // notify user
        view.alert(e.getMessage());
    }
}
Brian K Blain