问题
Which exception would I use in a try/catch to find out when the user has inputted data in the wrong format?
Example:
try
{
string s = textBox1.Text;
// User inputs an int
// Input error
MessageBox.Show(s);
}
catch(what exception)
{
MessageBox.Show("Input in wrong format");
}
Thanks
回答1:
Don't do this. It's a misuse of exception handling. What you are attempting to do is considered coding by exception, which is an anti-pattern.
An exception is exactly what it sounds like, an exception to the norm. It's defined by something you either haven't accounted for, or simply can't account for through traditional validation. In this situation, you can definitely account for a format issue ahead of time. If you know there is a possiblity that the inputted data will be in the wrong format, check for this case first. e.g.
if(!ValidateText(textBox1.text)) // Fake validation method, you'd create.
{
// The input is wrong.
}
else
{
// Normally process.
}
回答2:
You should avoid using Exceptions as flow control.
If you want a textbox to be an int, this is where int.TryParse() method comes in handy
int userInt;
if(!TryParse(textBox1.Text, out userInt)
{
MessageBox.Show("Input in wrong format");
}
回答3:
You can go with Exception ex
to catch all exceptions. If you want to catch a more specific one, though, you'll need to look at the documentation for whatever functions you are using to check the validity of the input. For example, of you use int.TryParse()
, then you will want to catch FormatException
among others (see: http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx for more information).
回答4:
You can create your own exception like ↓
public class FormatException : Exception
And In your source , it might be...
if (not int) throw new FormatException ("this is a int");
Then , In your catch ...
catch(FormatException fex)
来源:https://stackoverflow.com/questions/6681514/c-sharp-catch-exception