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
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.
The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
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.
}
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");
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With