Arco3
Arco3

Reputation: 343

try catch for a specific character on input in textbox

My code currently looks like this:

private void logBtn1_Click(object sender, EventArgs e)
{
    String email = textBox1.Text;
    String password = textBox2.Text;

    if (email.Contains("@"))
    {
        MessageBox.Show("Valid email!");
    }
    else
    {
        MessageBox.Show("Please enter a valid email address");
    }
}

I'd like to be able to use a try-catch to display an error message if the email string contains the "@" character - is this possible? I'm aware that it might not be a good way of doing this, and that checking for an @ character isn't really a good way to verify that an input is a legit email, but I'd still like to be able to perform this with a try catch if possible.

Upvotes: 2

Views: 1095

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156998

I'd still like to be able to perform this with a try catch if possible

You can, but you shouldn't. try...catch blocks are for uncontrolled exceptions, like a disk that is full so a file can't be written or similar situations. You don't want to use this because it is deteriorating for your performance.

If you can code this out without try...catch, you should. When I look at your code, I think it almost does all it can do to make the check right. I would just add a null check.

Upvotes: 1

user5441558
user5441558

Reputation:

If you must use a try catch you could do something like:

void ValidateEmail(string email) {
    if (!email.Contains("@"))
        throw new FormatException();
}

And surround the call to that code within a try catch.

However, I cannot really find a good reason why you'd want to do this.

Upvotes: 1

Related Questions