views:

117

answers:

2

I want to use custom exception handling, for example

instead of using (Exception ex) i want to use (LoginException ex) or (RegistrationException ex) or (SomeNameException ex)

is it possible to design such custom exception handling in ASP.NET webforms?

A: 

You mean something like:

try{
  somefunc();
}catch(LoginException ex){

}catch(RegistrationException ex){

}catch(SomeNameException ex){

}

Or do you mean coding the classes to throw the exceptions?

Psytronic
yes i want to code something like this
rs
+1  A: 

Yes but what you need to do is first create your own custom exceptions. You need to derive your exception from the Exception base class. Heres an example:

[Serializable]
public class LoginFailedException: Exception
{
    public LoginFailedException() : base()
    { 
    }

    public LoginFailedException(string message) 
        : base(message) 
    { 
    }

    public LoginFailedException(string message, Exception innerException) 
        : base(message, innerException) 
    { 
    }

    protected LoginFailedException(SerializationInfo info, StreamingContext context) 
        : base(info, context) 
    { 
    }
}

Then in your code, you would need to raise this exception appropriately:

private void Login(string username, string password)
{
     if (username != DBUsername && password != DBPassword)
     {
          throw new LoginFailedException("Login details are incorrect");
     }

     // else login...
}

private void ButtonClick(object sender, EventArgs e)
{
     try
     {
           Login(txtUsername.Text, txtPassword.Text);
     }
     catch (LoginFailedException ex)
     {
           // handle exception.
     }
}
James
Yes thank you, this is what i was looking for.
rs