C # Catch Exception

What exception would I use in try / catch to find out when the user entered the 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");
}

thank

+5
source share
4 answers

Do not do that. This is the misuse of exception handling. What you are trying to do is considered an exception encoding, which is anti-pattern .

, , . , , . , , . , , , . .

if(!ValidateText(textBox1.text)) // Fake validation method, you'd create.
{
  // The input is wrong.
}
else
{
  // Normally process.
}
+25

.

, int, int.TryParse()

int userInt;
if(!TryParse(textBox1.Text, out userInt)
{
    MessageBox.Show("Input in wrong format");
}
+10

Exception ex, . , , , , . , int.TryParse(), FormatException (. http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx ).

+2
source

You can create your own exception, for example ↓

public class FormatException : Exception

And at your source it could be ...

if (not int) throw new FormatException ("this is a int");

Then, in your catch ...

catch(FormatException fex)
+1
source

All Articles