异常 - 当方法引发多个异常时区分异常
我得到了这个引发相同类型异常的类,我如何捕获此异常并显示适当的错误消息。这就是我现在所做的。
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");
}
}
我执行以下操作,
try
{
}
catch(ArgumentException ex)
{
if(ex.Message.contains("Your old or"))
{
messagebox.show("Either your old or new password is empty or null")
}
...
}
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")
}
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的示例并不能真正证明自定义异常的合理性。我说只显示原始消息。
但是,如果您确实想走自定义异常的道路,那么另一种选择是创建一个自定义异常,它采用带有所有不同选项的
enum
,如下所示:Your example does not really justify custom exceptions. I say just display the original message.
However, if you really want to go down the path of custom exceptions, then another option is to create a single custom exception that takes an
enum
with all the different options, like such:您可能会考虑抛出不同的异常类型。如果您希望坚持使用库异常类型,则在旧密码或新密码为 null 或为空时,
ArgumentNullException
是合适的。或者,您可以考虑使用更具体的错误定义自己的异常类型(可能类似于 WCF 中的FaultExceptions),或者在自定义异常中包含资源标识符(以确保 I18N 兼容):然后像这样使用:
You might consider throwing different exception types. If you wished to stick with the library exception types an
ArgumentNullException
would be appropriate if the old or new password is null or empty. Alternatively you may consider defining your own exception types with a more specific error (perhaps similar to FaultExceptions in WCF), or including a resource identifier in your custom exception (to ensure I18N compatible):Then used like so:
您可以像这样创建自定义异常:
然后可以像这样使用它们:
然后您可以在 try catch 语句中处理它们,如下所示:
因此您可以用不同的方式处理不同类型的异常。希望这就是您正在寻找的。
You can create custom exceptions like this:
They can then be used like this:
Then you can handle them in a try catch statement like this:
So you can handle different types of exceptions in different ways. Hope that's what you were looking for.