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?

3
  • Dup stackoverflow.com/questions/1573130/… Commented Oct 16, 2009 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: stackoverflow.com/questions/1573130/… Commented Oct 16, 2009 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 !! Commented Oct 16, 2009 at 14:41

2 Answers 2

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.
     }
}
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.