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?

rs.
  • 26,707
  • 12
  • 68
  • 90
  • Dup http://stackoverflow.com/questions/1573130/net-throwing-custom-exceptions – andrewWinn Oct 16 '09 at 14:21
  • 1
    This isn't really a duplicate, but it is related to that question. Rahuls, I'd look specifically at this answer, and the links contained therein: http://stackoverflow.com/questions/1573130/net-throwing-custom-exceptions/1573156#1573156 – John Rudy Oct 16 '09 at 14:32
  • @anderewWinn , please read the question, I dont see requester asking about pros and cons of custom exceptions !! Question is rather Custom Exceptions are possible !! not pros and cons of it !! – Akash Kava Oct 16 '09 at 14:41

2 Answers2

3

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
  • 80,725
  • 18
  • 167
  • 237
0

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
  • 6,043
  • 5
  • 37
  • 56