C#Catch Exception
我会在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"); }
谢谢
不要这样做。 这是对exception处理的误用。 你试图做的是被视为exception编码 ,这是一种反模式 。
一个例外就是它的声音, 这是常态的一个例外 。 它由您未考虑的东西定义,或者根本无法通过传统validation来解释。 在这种情况下,您肯定可以提前解决格式问题。 如果您知道输入的数据可能格式错误,请先检查此情况。 例如
if(!ValidateText(textBox1.text)) // Fake validation method, you'd create. { // The input is wrong. } else { // Normally process. }
您应该避免使用Exceptions作为流控制。
如果你想让一个文本框成为一个int,这就是int.TryParse()方法派上用场的地方
int userInt; if(!TryParse(textBox1.Text, out userInt) { MessageBox.Show("Input in wrong format"); }
您可以使用Exception ex
来捕获所有exception。 但是,如果要捕获更具体的一个,则需要查看文档,了解用于检查输入有效性的任何函数。 例如,您使用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(FormatException fex)