0

I got this class which raises same type of exception, how do i capture this exception and display appropriate error message. Here is what i do now.

public bool ChangePassword(oldPassword,newPassword)
{

  if(oldPassword != savedInDatabase)
{
  throw new ArgumentException("Your old password is not same as one saved in our database")
}

  if(string.IsNullOrEmpty(oldPassword) || string.IsNullOrEmpty(newPassword))
{
 throw new ArgumentException("Your old or new password is empty of null");
}

}

and i do the below,

try
{
}
catch(ArgumentException ex)
{
 if(ex.Message.contains("Your old or"))
{
  messagebox.show("Either your old or new password is empty or null")
}
...
}
4

3 回答 3

2

您可能会考虑抛出不同的异常类型。如果您希望坚持使用库异常类型,ArgumentNullException那么如果旧密码或新密码为空或为空,则将是合适的。或者,您可以考虑使用更具体的错误定义自己的异常类型(可能类似于 WCF 中的 FaultExceptions),或者在自定义异常中包含资源标识符(以确保 I18N 兼容):

public class ResourceableException : Exception
{
  public string ResourceKey { get;set; }
}

然后像这样使用:

try { ... }
catch (ResourceableException e)
{
  messagebox.Show(ResourceManager.GetResource(e.ResourceKey));
}
于 2012-01-16T13:01:48.017 回答
2

您的示例并不能真正证明自定义异常是合理的。我说只是显示原始消息。

但是,如果您真的想走自定义异常的道路,那么另一种选择是创建一个自定义异常,它enum采用所有不同的选项,例如:

public class PasswordException : Exception
{
    public PasswordException(PasswordResult result) : base() { }
    public PasswordException(PasswordResult result, string message) : base(message) { }
    public PasswordException(PasswordResult result, string message, Exception innerException) : base(message, innerException) { }
}

public enum PasswordResult
{
    Success = 0,
    PasswordMismatch,
    PasswordEmpty,
    // and so forth
}
于 2012-01-16T13:19:54.670 回答
1

您可以像这样创建自定义异常:

public class PasswordEmptyOrNullException : Exception
{
    public PasswordEmptyOrNullException(string message)
        : base(message)
    {

    }
}

public class OldPasswordNotFoundException : Exception
{
    public OldPasswordNotFoundException(string message)
        : base(message)
    {

    }
}

然后可以像这样使用它们:

throw new PasswordEmptyOrNullException("A message");

然后你可以像这样在 try catch 语句中处理它们:

try
{
}
catch (PasswordEmptyOrNullException ex)
{
    // Do stuff
}
catch (OldPasswordNotFoundException ex)
{
    // Do stuff
}

所以你可以用不同的方式处理不同类型的异常。希望这就是你要找的。

于 2012-01-16T13:08:52.090 回答