【发布时间】:2016-04-22 11:44:49
【问题描述】:
目前正在处理一个小项目,其中包括一个注册表表单,用户可以在其中注册登录。我有错误提供程序,它会告诉用户他们输入的信息是否不正确。出于某种原因,这些异常不再被处理,即使它们是前一段时间的。
这是用户按下“注册按钮”时的代码
private void btnRegister_Click(object sender, EventArgs e)
{
//Try - Catch Statements
//Try to set the forename
try
{
player1.Forename = txtForename.Text;
player2.Forename = txtForename.Text;
errForename.Icon = Properties.Resources.Correct;
errForename.SetError(txtForename, "OK");
}
catch (NewException exc)
{
errForename.SetError(txtForename, exc.MessageM);
}
然后它会为其他详细信息执行此操作,例如姓氏、用户名。
这里是 User 类的 getter 和 setter
public string Forename
{
get
{
return forename;
}
set
{
bool okChar = OnlyChars(value, "Forename");
if (okChar == true)
forename = value;
else
{
throw new NewException(errorMessage);
forename = null;
}
}
}
最后是我写的 NewException 类
namespace Colludia
{
class NewException : Exception
{
private string messageM;
public NewException() : base()
{
}
public NewException(string message) : base(message)
{
messageM = message;
}
public string MessageM
{
get { return messageM; }
set { messageM = value; }
}
}
}
【问题讨论】:
-
你应该not use exceptions for your normal control flow。您可以轻松检查字符串是否仅包含字符。不需要例外。控制流的异常类似于非本地 goto 语句。
-
欢迎来到 Stack Overflow。请将您的代码重写为minimal reproducible example - 另请注意,使用自动实现的属性将显着减少
NewException类中的代码。最后,您希望throw语句之后的语句如何执行? -
异常类中的MessageM变量也完全没用;它只是已存储消息的副本。
okCharboolean 也不需要在那里;你可以马上写if (OnlyChars(value, "Forename"))。 -
你的异常没有被处理是什么意思?很可能你只是得到不同类型的异常,而不是你期望的那个(NewException)。
-
请注意,在您的代码
throw new NewException(errorMessage); forename = null;中,第二条语句将永远不会被执行。更改顺序。
标签: c# exception exception-handling