在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");
}
谢谢
在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");
}
谢谢
不要这样做。这是滥用异常处理的行为。你试图做的被称为 异常驱动编程,这是一种反模式。
异常就是它听起来的意思,即规范之外的情况。它由你没有考虑到的某些事物定义,或者仅仅是无法通过传统的验证来解释。在这种情况下,你肯定可以提前检查数据格式问题。例如:
if(!ValidateText(textBox1.text)) // Fake validation method, you'd create.
{
// The input is wrong.
}
else
{
// Normally process.
}
避免使用异常来控制程序流程。
如果您想让文本框变成一个整数,这就是int.TryParse()方法发挥作用的地方。
int userInt;
if(!TryParse(textBox1.Text, out userInt)
{
MessageBox.Show("Input in wrong format");
}
Exception ex
来捕获所有异常。如果您想要捕获更具体的异常,那么您需要查看您正在使用的函数的文档以检查输入的有效性。例如,如果您使用int.TryParse()
,那么您将需要捕获FormatException
等其他异常(参见:http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx了解更多信息)。您可以像下面这样创建自己的异常:
public class FormatException : Exception
if (not int) throw new FormatException ("this is a int");
然后,在你的 catch 中...
catch(FormatException fex)