Should I use a "Try-catch" to identify if a password is wrong?

Asked

Viewed 785 times

9

On the screen of login, carry out the verification in the bank by means of a select, and I’m using the catch to capture this exception.

It is correct to use the catch for that guy?

if (Usuario != string.Empty && Password != string.Empty)
        {
            try
            {
                consql._sql = @"SELECT id_usu FROM login WHERE usuario = @usuario AND password = @password";
                //consql._sql = @"SELECT COUNT(id_usu) FROM login WHERE usuario = @usuario AND password = @password";
                SqlCommand cmd1 = new SqlCommand(consql._sql, sqlconn);
                cmd1.Parameters.Add("@usuario", SqlDbType.VarChar).Value = Usuario;
                cmd1.Parameters.Add("@password", SqlDbType.VarChar).Value = Password;
                sqlconn.Open();
                int count_id = (int)cmd1.ExecuteScalar();

                if (count_id > 0)
                {
                    Sessaosistema.UsuarioId = count_id;
                    Sessaosistema.NomeUsuario = Usuario;

                    MessageBox.Show("Usuario logado com sucesso", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    Menu_Inicial mi = new Menu_Inicial();
                    mi.Show();
                    this.Hide();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Usuário ou Senha incorretos" + "\n" + "Revise os dados inseridos e tente novamente", "Falha de Logon", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                sqlconn.Close();
            }
        }

4 answers

19


If you have a memory allocation problem, the user, and consequently you, will receive a message saying "Incorrect User or Password". You think this is right?

If the database stops working it will inform you that the password is wrong. That’s what you want?

If you have the various other types of exceptions throughout the code - let’s say passing does too many things and mixes responsibilities - including programming errors, wants the user to be notified that his password is wrong?

Capture Exception it’s almost always a mistake.

In fact, from what I understood of the code, the exception has nothing to do with user error and password, what determines if the password is wrong is the condition count_id > 0, that is, if this is false the password is wrong. The use of the exception does not make any sense. Almost always does not, especially to control normal flow of code, where the if is more appropriate.

It is best to take this exception, perhaps a more specific one elsewhere makes some sense. And wear a using in sqlconn looks better.

  • Thanks friend for the explanation. I’ll adjust my code.

  • Good question and great answer. And, just to point out what many programmers do: Try / Catch is not If / Else

4

The Try/Catch most used to catch some error from exception in the system type conversion problem these things.

My suggestion is that you check the Count of the search in the database. If it returns 0, is that there is no user. So you display the message "Incorrect User or Password", and leaving the try and catch for even syntax bug.

2

From what I saw in your code, I think it would be nice for you to use the try/catch with the intention of capturing the exception if the database connection is not established, so you can present a message on screen to the user stating the same.

  • Diego, exactly, after talking to the staff I redid the catch code to catch this kind of exception.

2

Exceptions and Try Catch!

First, answering your question, yes I think you can and should use Try catch to capture the password error, but with a question, you should create a correct Exception for this:

public class LoginPassInvalidException : Exception
{
    public LoginPassInvalidException() : base("Login ou Senha Inválidos!")
    {
    }

    public LoginPassInvalidException(string message) : base(message)
    {
    }

    public LoginPassInvalidException(string message, Exception innerException) : base(message, innerException)
    {
    }

    protected LoginPassInvalidException(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }
}

After this do correct Exception treatment in the case: LoginPassInvalidException !!!

To have a functioning but improved use this way:

        try
        {
            consql._sql = @"SELECT id_usu FROM login WHERE usuario = @usuario AND password = @password";
            //consql._sql = @"SELECT COUNT(id_usu) FROM login WHERE usuario = @usuario AND password = @password";
            SqlCommand cmd1 = new SqlCommand(consql._sql, sqlconn);
            cmd1.Parameters.Add("@usuario", SqlDbType.VarChar).Value = Usuario;
            cmd1.Parameters.Add("@password", SqlDbType.VarChar).Value = Password;
            sqlconn.Open();
            int count_id = (int)cmd1.ExecuteScalar();

            if (count_id > 0)
            {
                Sessaosistema.UsuarioId = count_id;
                Sessaosistema.NomeUsuario = Usuario;

                MessageBox.Show("Usuario logado com sucesso", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Menu_Inicial mi = new Menu_Inicial();
                mi.Show();
                this.Hide();
            }
            else
            {
                throw new LoginPassInvalidException();
            }
        }
        catch (LoginPassInvalidException ex)
        {
              MessageBox.Show(ex.Message + "\n" + "Revise os dados inseridos e tente novamente", "Falha de Logon", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Prezado usuário ocorreu uma ação não prevista, informe ao administrador do sistema: " + ex.Message, "Ação não prevista", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            sqlconn.Close();
        }

In short, programmers generally do not use Exceptions as a resource that can be programmed, but the correct thing is to create Exceptions for each error of your system and treat them as well as those of the framework itself!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.