【发布时间】:2012-02-11 09:57:09
【问题描述】:
我得到了这个引发相同类型异常的类,我如何捕获这个异常并显示适当的错误消息。这就是我现在要做的。
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")
}
...
}
【问题讨论】:
-
为什么不直接显示来自原始异常的消息?搜索这样的字符串通常是个坏主意。
-
@Oded 我可以,但是我如何识别
ArgumentNullException类型的其他异常。我认为更好的主意是使用友好的异常消息并显示它们。 -
@PeetBrits
Why don't you just display the message from the original exception这正是我现在的想法。只需使用友好的消息而不是检查字符串
标签: c# exception exception-handling error-code