我会在try / catch中使用哪个例外来找出用户输入错误格式的数据的时间?
示例:
try
{
string s = textBox1.Text;
// User inputs an int
// Input error
MessageBox.Show(s);
}
catch(what exception)
{
MessageBox.Show("Input in wrong format");
}
由于
答案 0 :(得分:25)
不要这样做。这是对异常处理的误用。您尝试执行的操作被视为按例外编码,即anti-pattern。
异常恰如其分,异常。它由您未考虑的东西定义,或者根本无法通过传统验证来解释。在这种情况下,您肯定可以提前解决格式问题。如果您知道输入的数据可能格式错误,请先检查此情况。 e.g。
if(!ValidateText(textBox1.text)) // Fake validation method, you'd create.
{
// The input is wrong.
}
else
{
// Normally process.
}
答案 1 :(得分:10)
您应该避免使用Exceptions作为流量控制。
如果你想让一个文本框成为一个int,这就是 int.TryParse()方法派上用场的方法
int userInt;
if(!TryParse(textBox1.Text, out userInt)
{
MessageBox.Show("Input in wrong format");
}
答案 2 :(得分:2)
您可以使用Exception ex
来捕获所有异常。但是,如果您想捕获更具体的一个,则需要查看文档以了解用于检查输入有效性的任何函数。例如,您使用int.TryParse()
,然后您需要捕获FormatException
等其他内容(有关详情,请参阅:http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx)。
答案 3 :(得分:1)
您可以创建自己的例外,例如↓
public class FormatException : Exception
在你的来源中,它可能是......
if (not int) throw new FormatException ("this is a int");
然后,在你的捕获......
catch(FormatException fex)