Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have been working on a project with layered architecture. I am confused at a stage where to catch and where to throw exception. here is the scenario

presentation layer:
C#
protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                userName = txtUserName.Text;
                passWord = txtPassword.Text;
                dtLoginDetail = UserDetail.Login(userName, passWord);
                if (dtLoginDetail.Rows.Count > 0)
                {
                    returnUrl = "~/AuthenticatedUsers/Home.aspx";
                    Response.Redirect(returnUrl, false);
                }
                else
                {
                    lblLoginMessage.Text = "Invalid Username or Password!";
                    error = true;
                }
            }
            catch (NullReferenceException rx)
            {
                lblLoginMessage.Text = "Error connecting to server! Please check your internet connection";
                error = true;
            }
            catch (MySqlException mx)
            {
                lblLoginMessage.Text = "Sorry, Failed to Login. Please try after some time.";
                error = true;
            }
            if (error)
            {
                //show error
            }
      }


business layer:
C#
public DataTable Login(string username, string password)
{
    DataTable dtLoginDetails = new DataTable();
    Login loginAction = new Login();
    dtLoginDetails = loginAction.ValidateUser(username, password);
    return dtLoginDetails;
}


Data Layer:
C#
public DataTable ValidateUser(string username, string password)
{
    DataTable dtLoginDetails = new DataTable();

    try
    {
        string selectQuery = "SELECT user_id FROM user_details WHERE username='" + username + "' AND password='" + password + "' LIMIT 1";
        dtLoginDetails = connection.SelectCommand(selectQuery);
        return dtLoginDetails;
    }
    catch (NullReferenceException rx)
    {
        throw;
    }
    catch (MySqlException mx)
    {
        throw;
    }
}


Please let me know what is the best practice in giving the try catch in layer? should i throw specific error as i did in the baove code?

Thanks,
Amrutha
Posted
Updated 8-Jun-14 23:51pm
v2

Hi Friend,

you can make code with try catch whenever you have possibility to error occur(any Layer).
if you want to display error Message then write "throw ex" from Sub Layer(Business layer,Data Layer).
And Display this Error Message From presentation layer in Catch Block Using ex.Message.
 
Share this answer
 
v2
Hi Amrutha,

Its not a good practice to re-throw an error so please avoid it.

What you required to do when a error occurred there are several ways to handle it but you should know whats the actual requirement is.
In your case I think enum will do the trick.

Create a enum

C#
public enum ErrorTypes
{
NoError=0,
SQL=1,// SQL related 
Logical=2,//Business logic
Data=4, // Database related 
ErrorUndefine=8
// So on as you need 
}
// function signature for Business and Data Layer: add a out parameter 

public bool LogIn ([Your parameters],out ErrorTypes Error);


Now put try catch block in Business and Data Layer Like

C#
try {
}catch(Exception ex)
{
Error=ErrorUtil.SetErrorType(ex);
}
// The function 

public class ErrorUtil
{
public static ErrorTypes SetErrorType(Exception ex)
{
  if(ex is SQLException)
    {
      return ErrorTypes.SQL;
    }
// So on 
}
}
// After call of Business or Data layer just check what kind of error its returning.


But always remember that its better to check validity of data rather that waiting for a run time error.

Thanks
Suvabrata
 
Share this answer
 
Comments
AmruthaNair 9-Jun-14 23:22pm    
Hi, Thanks for the responce.
I have also read like re-throwing is not a best practice. Can you please specify what is the disadvantage in re-throwing? Will there be any performance issues?
Suvabrata Roy 6-Nov-14 3:40am    
Yes there are some performance related issue.

Exception mean a situation where CLR dose not know what to do and it will break all the flow of your program one by till it reach the catch block, now if you re-throwing it so you are forcing CLR to do it twice whereas you an do it using some flag so its better to use flag or Exception handling engine to manage your exception rather then re-throwing.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900